Can someone explain either in English or in C/C++/Java whatever.. how the steps. I actually would prefer to see something like append or reverse.. I'm mostly just manipulating lists of variables instead of integers.. (I've tried to work through append like 10 times.. ugh).

Best Answer

The free online book "Learn Prolog Now" has a section dedicated to explaining the steps that append performs:

comments:

this is the best step by step answer I've seen.. and I've looked through several books. Makes far more sense now after looking at a trace

Other Answer1

append(A, B, R) means that R is the result of appending A to B.

The base case

append([], X, X).

says that if A = [] and B = X then R = X = B: an empty list A appended to some other list B is equal to B.

The recursive case

append([X | Y], Z, [X | W]) :- append(Y, Z, W).

says that if A = [X | Y] is a non-empty list to append to B = Z, and if W is Y appended to Z, then R = [X | W].

Another way of saying it is: to append a non-empty list A to another list B, first append the tail of A to B and then add the head of A to the front of the list.

comments:

this follows the best format IMO. I've seen numerous ones like this just not translated to english for recursion. is the recursive version always read from left to right.. aka ", = and" thus operation perform in order left to right.. ([x|y], z, [x|w]). but only if append(y,z,w) holds.

I'll immediately admit that this is horridly ugly C++, but it's direct translation of the Prolog program, except that lists are simulated using arrays and a depth counter.

Other Answer3

Recursion in prolog is pretty much identical to recursion in any other language. The trick with prolog is that

every variable is local, and,

once unified, variables cease to be variables. They can never change value.

This means that you'll often need to build what I'll call "worker" predicates that do that the actual work required and carry around 1 or more variables that act as working storage. Here is an implementation of sum/2 to sum a list of integers: