Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

recursion in prolog (on lists)

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...