Prolog101(13)

递归与尾递归:

%需要栈记录中间结果
factorial_1(1,1).
factorial_1(N,F):- 
N > 1,
NN is N - 1,
factorial_1(NN,FF),
F is N * FF.

%不需要记录中间结果
factorial_2(1,F,F). 
factorial_2(N,T,F):- 
N > 1,
TT is N * T,
NN is N - 1,
factorial_2(NN,TT,F).
?- factorial_1(5,X).
X = 120 .

?- factorial_2(5,1,X).
X = 120 .
%用栈记录中间结果
reverse_1([],[]). 
reverse_1([H|T],Rev):- 
reverse_1(T,TR), 
append(TR,[H],Rev).

%借助变量记录中间结果
reverse_2([], Rev, Rev). 
reverse_2([H|T], Temp, Rev) :- 
reverse_2(T, [H|Temp], Rev). 
?- reverse_1([a,b,c,d,e],X).
X = [e, d, c, b, a].

?- reverse_2([a,b,c,d,e],[],X).
X = [e, d, c, b, a].

Comments are closed.