Associative list in Prolog

半世苍凉 提交于 2019-12-11 01:13:37

问题


i m doing associative list in prolog i seen this topic but i dont understand the code.

Associative Lists in Prolog

For checking list is associative isn't enough do this:

 lists([_X, _Y]).
 lists([[H|_T]|L],[H|T]):- lists(L,T).

Because for first /1 i check if have element in this way [a,3] and /2 take list of list [[a,4],[a,3]] in this way. so first pass call list/2 on [a,3], and check true for base case, and after call [a,4] and call true for base case too.

I wrong something, but i don't see,

Anyone can clarify me?


OP's update of 2019-01-01 10:40:47Z:

I try to resolve in this way:

islist([_X,_Y]).
islist([_X|T]):- islist(T).

In this case accept just input in this way

[[k,v],[k,v],[k,v]]

but accept all input like this:

  • [a]
  • [k,v,v,v]
  • [[k,v],[k,v],[k,v,v]]

So my problem remains.


回答1:


From the linked question:

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

Just write this down in Prolog:

associative_list(L) :- L = [].
associative_list(L) :- K=K, V=V, associative_list(A), L = [[K, V] | A].

Of course Prolog as a programming language has operational concerns as well as its logical semantics, so the last line is better written instead as

associative_list(L) :- L = [[_K, _V] | A], associative_list(A).

An idiomatic way to write this is

associative_list([]).
associative_list([[_, _] | A]) :- associative_list(A).


来源:https://stackoverflow.com/questions/53989755/associative-list-in-prolog

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