Please send questions to
st10@humboldt.edu .
%--------
% some more recursive examples...
% last modified: 03-29-11
%--------
%--------
% from the clicker question...
% (note, though -- sumlist is a predicate for which the first
% parameter must be instantiated at the time of the call...)
sumlist([], 0).
sumlist([H|T], Sum) :- sumlist(T, TSum),
Sum is H + TSum.
%--------
/* rev_countlist(A, B) is true if B is the list of A .. 1) */
rev_countlist(0, []).
rev_countlist(Num, [Num|Rest]) :-
Num > 0,
Next is Num-1,
rev_countlist(Next, Rest).
%--------
% adapted from Prolog tutorial posted at
% http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/pt_framer.html
factorial(0,1).
factorial(Num,NumFactorial) :-
Num > 0,
PrevNum is Num-1,
factorial(PrevNum, PrevNumFactorial),
NumFactorial is Num*PrevNumFactorial.
%--------
% adapted from:
% http://www.cse.unsw.edu.au/~billw/cs9414/notes/write-recursive-proc.html
% lastitem(List, Last)
% Binds Last to the item at the end of List.
% List must be instantiated at the time of call, and must not be empty.
% Example of use:
% ?- lastitem([a,b,c,d], X).
% X = d
%% base case: list with just one item.
lastitem([OnlyOne], OnlyOne).
%% recursive case: ignore first item, seek last item of rest of list
lastitem([First|Rest], Last) :-
lastitem(Rest, Last).