Prolog 中的关联列表 [英] Associative Lists in Prolog

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

问题描述

我的任务是用列表实现地图.我们将关联列表定义如下:

my task is to implement maps with lists. We defined associative lists as follows:

[] 是列表,k 是键,v 是值,a 是关联列表,那么 [[k, v] |a] 是一个关联列表.

[] is the list, k is a key, v is a value and a is an associative list, then [[k, v] | a] is an associative list.

所以现在我必须编写一个谓词,在其中检查给定参数是否是关联列表.例如:

so now ive got to write a predicate, in which it checks if the given argument is a associative list. for example:

?- test([[a,5]]). -> true., ?- test([[1],[2]]). -> false.

我真的很绝望,我希望有人可以帮助我

im really in despair, i hope someone can help me there

问候

推荐答案

我可以说 关联列表被实现为 AVL 树,而不是点对列表,尽管后者是可能的.

I may say that associative lists in SWI-Prolog are implemented as an AVL-trees, not as the lists of a dotted pairs, though the latter is possible.

那么,让我们试试你的方法吧.

So, let's try your way.

[] 是列表,k 是键,v 是值,a 是关联列表,则 [[k, v] |a] 是一个关联列表.

[] is the list, k is a key, v is a value and a is an associative list, then [[k, v] | a] is an associative list.

一个更正:

我建议 [[ k |v ] |a] 更紧凑并且更具关联性")

I'd suggest [[ k | v ] | a] that is more compact and is "more associative" )

is_assoc([]).
is_assoc([[K|V] | AL]) :- %corrected 29 apr 2018 19:00 gmt+3
    !, is_assoc( AL ).


put(KV, AL, AL0) :-
   KV = [K|V],
   get(K, AL, V),
   remove(KV, AL, AL_KV),
   put(KV, AL_KV, AL0).

put(KV, AL, [KV | AL]).

get(K, AL, V):-
   member([K|V], AL).

这篇关于Prolog 中的关联列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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