can someone please help me just w/ the basics on performing recursive prolog functions..
append([],X,X). % base
append([X|Y],Z,[X|W]) :- append(Y,Z,W). %recursive
% base case
addup([], 0). % sum of the empty list of numbers is zero
% recursive case: if the base-case rule does not match, this one must:
addup([FirstNumber | RestOfList], Total) :-
addup(RestOfList, TotalOfRest), % add up the numbers in RestOfList
Total is FirstNumber + TotalOfRest.
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).
You want to see it in C++?
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.
Recursion in prolog is pretty much identical to recursion in any other language. The trick with prolog is that
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:
Here is an implementation in ANSI C that closely mirrors the above prolog code:
The free online book "Learn Prolog Now" has a section dedicated to explaining the steps that append performs:
http://cs.union.edu/~striegnk/learn-prolog-now/html/node47.html#subsec.l6.defining.append
append(A, B, R)
means thatR
is the result of appendingA
toB
.The base case
says that if
A = []
andB = X
thenR = X = B
: an empty listA
appended to some other listB
is equal toB
.The recursive case
says that if
A = [X | Y]
is a non-empty list to append toB = Z
, and ifW
isY
appended toZ
, thenR = [X | W]
.Another way of saying it is: to append a non-empty list
A
to another listB
, first append the tail ofA
toB
and then add the head ofA
to the front of the list.