Recursively Building Lists
From: Stephen Andrew Church (sachurch_at_bigpond.com)
Date: 04/23/04
- Previous message: Maciek: "Working on different databases"
- Next in thread: vannoord_at_let.rug.nl: "Re: Recursively Building Lists"
- Reply: vannoord_at_let.rug.nl: "Re: Recursively Building Lists"
- Reply: Nameless: "Re: Recursively Building Lists"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 23 Apr 2004 00:47:27 GMT
Greetings,
I would very much appreciate some help in understanding how it is one
constructs lists recursively. I believe I have a reasonable grasp of how
lists may be traversed recursively by passing the list tail as an argument
in succesive recursive calls, and terminating the recursion with a match to
an empty list argument.
However, I have experienced considerable difficulty in going the opposite
way, so to speak, constructing a list recursively. Here is the code I have
been using.
%% Both these predicates have been used with the same result
genlist(0,L0,L0).
%%genlist(0,L0,L1) :- !, L0 = L1.
genlist(N0,L0,L1) :- addtoend(L0,N0,L1), N1 is N0-1,
genlist(N1,L1,L2).
addtoend([],E0,[E0]).
addtoend([H0|T0],E0,[H0|T1]) :- addtoend(T0,E0,T1).
If I submit the query.
genlist(5, [], L).
L is only ever instantiated to [5], and the whole of the constructed list,
[1,2,3,4,5], is not returned.
If a patient soul could please explain not only where I am in error, but
describe the usual or commonly accepted recursive technique for performing a
task such as this, I would be immensely grateful.
Stephen
- Previous message: Maciek: "Working on different databases"
- Next in thread: vannoord_at_let.rug.nl: "Re: Recursively Building Lists"
- Reply: vannoord_at_let.rug.nl: "Re: Recursively Building Lists"
- Reply: Nameless: "Re: Recursively Building Lists"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|