Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the '|' character in prolog append rather than split a list?

My example is using the append functor:

append([],L,L). 
append([H|T],L2,[H|L3])  :-  append(T,L2,L3).

//append([123],[abc],L3). this is the query

What really confuses me is the [H|L3] list. Form what I read, that takes off the head, so how is that appending it to the list. When it recurses through the list, and starts coming back, how is that appended? Thanks in advance.

like image 722
Andy Avatar asked Jan 18 '26 21:01

Andy


1 Answers

The notation [H|T] is syntactic sugar for '.'(H, T). So it is a functor with the name . – a single dot and two arguments. Consider:

?- [1,2,3] = [X|L].
   X = 1, L = [2,3].

Here we ask, if there is a solution to the equation [1,2,3] = [X|L]. And, yes, there is exactly one solution which is described with these two answer substitutions. The process of solving this equation is called unification. This process subsumes reading, selecting and writing of data structures. So, you can call this "taking off the head", but you will miss the generality behind. After all:

?- X = 1, L = [2, 3], M = [X|L].
   X = 1, L = [2,3], M = [1,2,3].

Here we constructed a new list out of a smaller one. But what is:

?- M = [X|L].
   M = [X|L].

This answer implies many solutions. For example, all lists of length 1 and longer.

Since you are looking at append/3, consider the following queries:

?- append(Xs, Ys, [X,Y,Z]).
?- append(Xs, Xs, Zs).
?- append(Xs, Ys, Zs)

More on list syntax.

like image 131
false Avatar answered Jan 21 '26 12:01

false



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!