Bob Smith
Bob Smith

Reputation: 3

Building a List Recursively Prolog

This is a pretty simple problem, and hopefully it has a simple answer as well. I am trying to generate a list of numbers up to N. For example, for N = 3, the program would output [0,1,2].

My problem is that my code gives me [[0,1,2]]. I need the list to be only one list, not nested inside another.

Here is my code:

genNhelp2(N,N,L,L).
genNhelp2(N,C,L,R) :-
    C < N,
    append(L,C,Res),
    C1 is C + 1,
    genNhelp2(N,C1,Res,R).

genN(N,R) :- 
    genNhelp2(N,0,[],R). 

I also tried this, with the same results:

genNhelp(N,N,[]).
genNhelp(N,C,[C|R]) :- 
    C < N,
    C1 is C + 1,
    genNhelp(N,C1,R).

genN(N,R) :-
    genNhelp(N,0,R).

This seems like an easy fix, but I can't figure it out. Thanks!

Upvotes: 0

Views: 1003

Answers (3)

Nicholas Carey
Nicholas Carey

Reputation: 74257

Something like this ought to work:

gen_range(N,Ns) :-     % to generate a list of sequential numbers,
  gen_range(N,0,[],Ns) % - just invoke the helper, appropriately seeded
  .                    % - that's all there is to it.

gen_range(0,_,Ns,NS).        % succeed when the range is complete
gen_range(N,X,Ts,Ns) :-      % otherwise...
  N > 0 ,                    % - if the range is not yet complete
  N1 is N-1 ,                % - increment X
  X1 is X+1 ,                % - decrement N
  gen_range(N1,X1,[X|Ts],Ns) % - and recurse down.
  .                          % 

Upvotes: 0

Eugene Sh.
Eugene Sh.

Reputation: 18331

Do you mind changing your signature from genN/2 to genN/3, such that it will be more generic and simple?This way:

genN(X, X, [X]).

genN(From, To, [From|T]) :-
    From1 is From + 1,
    genN(From1, To, T).

Now to are able to do stuff like:

>> genN(0, 3, L).
L = [0, 1, 2, 3]

and even

>> genN(-2, 4, L).
L = [-2, -1, 0, 1, 2, 3, 4]

Upvotes: 2

Mark Reed
Mark Reed

Reputation: 95252

You don't really need the helper. How about this?

genN(0,[]).
genN(N,R) :- 
   N > 0,
   N1 is N-1,
   genN(N1,R1),
   append(R1,[N1],R).

Upvotes: 0

Related Questions