I am trying to further my understanding of Prolog, and how it handles list unification. So I am stuck with this example, that I know the answer as I execute the code, but I cannot understand how it works.
[X,a,X,f(X,a)|Y] = [Z,Z|Y]
The answer is:
X=Z
Z=a
Y=_
L=[a,f(a,a)|Y]
I know that the head unifies with the other head, so if I make some changes, like these:
let C=[X,a,X,f(X,a)]
let D=[Z,Z]
and the unification should go this way:
[C|Y]=[D|L]
so Y must be equal to L, not _, right? Can someone explain me this better and correct my mistake?
There's nothing special or unique about lists. A list is just the data structure ./2
. Prolog's list notation is just syntactic sugar on top of that. In a nutshell:
[]
is an atom and denotes the empty list.[a]
is exactly equivalent to .(a,[])
.[a,b]
is exactly equivalent to .(a,.(b,[]))
.The head/tail construct [Head|Tail]
is likewise syntactic sugar:
[H|T]
is exactly equivalent to .(H,T)
.Replace the list notation with the dot notation and your predicate will work exactly the same. Just not as convenient.