Associative Lists in Prolog

自闭症网瘾萝莉.ら 提交于 2019-12-08 07:38:59

问题


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

[] 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

greetings


回答1:


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.

[] 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.

One correction:

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).


来源:https://stackoverflow.com/questions/50069875/associative-lists-in-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!