且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Prolog-映射(关联数组)

更新时间:2023-11-26 08:09:16

这实际上取决于您要如何表示映射".在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.