Prolog-映射(关联数组) [英] Prolog- Mappings (Associative Arrays)

查看:82
本文介绍了Prolog-映射(关联数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习序言,想知道是否有人给我有关如何解决此问题的指导,这是该领域的第一门知识,知道如何解决此问题将真正帮助我进步.预先谢谢你.

I am studying prolog and was wondering if anybody give me guidance on how to go about doing this question, It's the first of many in this area and knowing how to do this question will really help me progress. Thank-you in advance.

使用Prolog定义谓词mapof(K,M,V),这样,当用K实例化为键的键和M实例化为映射的键时,mapof会将变量V实例化为值(或其中一个值) )与映射M中的K相关联.如果K不作为映射M中的键出现,则谓词应该失败.

Using Prolog define a predicate mapof(K, M, V) such that, when invoked with K instantiated to a key, and M instantiated to a mapping, mapof will instantiate the variable V to the value (or one of the values) associated with K in mapping M. The predicate should fail if K does not appear as a key in mapping M.

推荐答案

这实际上取决于您要如何表示映射".在Prolog中,事实表是最明显的方法.对于两个映射mn:

It really depends how you want to represent your "mapping". In Prolog, a table of facts is the most obvious approach. For two mappings m and n:

m(a, 1).
m(b, 2).
m(c, 3). % and so on

n(a, foo).
n(b, bar).
n(c, baz). % and so on

然后,您的mapof将类似于以下内容:

Then, your mapof would be something along the lines of:

mapof(K, m, V) :- m(K, V).
mapof(K, n, V) :- n(K, V).

或者也许:

mapof(K, M, V) :- call(M, K, V).

列表可以用来表示映射,如@Yasel所示,但是Prolog中的列表[a, b, c]是类似于.(a, .(b, .(c, [])))的嵌套术语.您通常不将关联数组表示为单链列表,对吧?

A list can be used to represent a mapping, as shown by @Yasel, but a list [a, b, c] in Prolog is a nested term like .(a, .(b, .(c, []))). You don't usually represent an associative array as a singly linked list, right?

在SWI-Prolog中,有一个库比对一个以Prolog术语表示的可回溯关联数组使用简单列表更好:

In SWI-Prolog there is a library that is better than using a simple list for a backtrackable associative array represented as a Prolog term: library(assoc). With it, you can do:

mapof(K, M, V) :- gen_assoc(K, M, V).

此库将关联数组表示为AVL树.您可以在SWI-Prolog代码源中找到另外两种关联的数组实现:一种使用不可回溯的RB树.

This library represents the associative array as an AVL tree. You can find in the SWI-Prolog code source two more associative array implementations: one using RB-trees, and one that uses non-backtrackable RB-trees.

如果您的关联数组中包含大约100个以上的键/值对,那么这里提到的所有三个库可能比简单的键/值对列表[k1-v1, k2-v2...]更有效.这并不意味着使用成对的列表并执行member(Key-Value, List_of_pairs)是错误的;这是用于简单案例的最便宜的解决方案.

All three libraries mentioned here are probably more efficient than a simple list of key-value pairs [k1-v1, k2-v2...] if your associative array has more than say around 100 key-value pairs in it. This doesn't mean that using a list of pairs and doing member(Key-Value, List_of_pairs) is wrong; it is the cheapest solution for simple cases.

这篇关于Prolog-映射(关联数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆