2

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.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
theantomc
  • 619
  • 2
  • 7
  • 32
  • That code in the answer you linked represents a key-value pair within the list as `[K|V]`, not `[K,V]`. If you want to use that code, write `[a|3]` instead of `[a,3]` for example. Your `lists` predicate has issues in that it does things differently. And your base case takes only one argument, whereas your recursive case has two arguments. – lurker Dec 31 '18 at 20:20
  • @lurker i would make a new code for understand the philosophy. I m new in prolog, i m on it. In the recursive case, i don't recall the same list of the list, but i need to maintain on element and pass at function the tail of the list of the list? – theantomc Jan 01 '19 at 09:46
  • 1
    kudos for staying engaged! – Will Ness Jan 01 '19 at 12:46

1 Answers1

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).
Will Ness
  • 70,110
  • 9
  • 98
  • 181