This was given as an example in a professor’s lecture:
append([ ], A, A).
append([A|B], C, [A|D]) :- append(B,C,D).
Build a list:
?- append([a],[b],Y).
Y = [ a,b ]
Break a list into constituent parts:
?- append(X,[b],[a,b]).
X = [ a ]
?- append([a],Y,[a,b]).
Y = [ b ]
I’ve spent 3 hours trying to grasp it and can’t. Hadn’t had any trouble with any prolog concepts preceding this slide. There is no further explanation provided, no other information. This is all. If someone could walk me through how this procedure works, I would love them til death do us part.
The first thing to understand is the
:-operator.Basically, whatever is on the right of
:-is a precondition. A good example is:This basically means that X and Y are siblings if there exists a parent Z such that Z is the parent of both X and Y.
This line basically means that appending something to an empty list returns the something. It’s the base case in the recursion.
This line means that appending C to an existing list with A and B returns a list with A and D given that appending C to B returns D.
So, what’s going on here is that Prolog returns the only possible value of
Ythat satisfies the two rules given the two initial values. Let’s think about how this happens. This would need to first be evaluated by the second rule. So[A|B]is[a]andCis[b].So with
[A|B]we have to go back to the first rule becauseBis empty list (it is[ ]). The first rule basically states that we can write[a]as[a|[ ]]and they are the same thing. So now we can go back to the second rule.Aisa,Bis[ ], andCis[b].So now let’s check the precondition of
append(B, C, D). This isappend([ ], [b], D). Once again, using the first rule, we can see thatDis also[b].So
Y, by the second rule definition, is[A|D]. Now that we knowDis[b], we know thatYis[a, b].I’ll only do one of the breaking apart since they’re basically the same thing.
So here, Prolog is going to return the only possible value of
Xso that the statement returns true. Let’s take a look at the second rule. So we know that[a, b]is[A|D]. This means thatAisaandDis[b]. We also know thatCis[b]. So now, we need to look at the precondition to figure out whatBis.append(B, C, D)translates toappend(B, [b], [b]). Now, using the first rule, we know thatBhas to be[ ]. So now we know that[A|B]is[a|[ ]]which is the same as[a]. Therefore,Xmust be[a].I hope this was a detailed enough explanation.