Banshee391
Banshee391

Reputation: 11

Changing output of Prolog from a list to individual values

I want to alter the following code so that genN(3,R) outputs: R=0. R=1. R=2.

Instead of a list R=[0,1,2]. How would I go about completing this?

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

Upvotes: 1

Views: 214

Answers (3)

user1812457
user1812457

Reputation:

from0_upto(N, R) :-
    succ(N0, N),
    between(0, N0, R).

Consider that it is not trivial (not impossible either) to write your own version of between/3 that behaves well in all corner cases. There are several attempts at this here on Stackoverflow, as well as an implementation in Prolog here: http://www.cs.otago.ac.nz/staffpriv/ok/pllib.htm (search for the string "between/3".

The Bottom Line

If you need a list, generate a list. If you need solution upon backtracking, generate solutions upon backtracking.

Upvotes: 2

joel76
joel76

Reputation: 5645

You can do :

gen(N, R) :-
    gen_one(N, 0, R).


gen_one(N, V, R) :-
    N > V,
    (   R = V; V1 is V+1, gen_one(N,V1,R)).

Upvotes: 2

repeat
repeat

Reputation: 18726

Use genN/2 and member/2 in conjunction, like this:

?- genN(3,Rs), member(R,Rs).
Rs = [0,1,2], R = 0 ;
Rs = [0,1,2], R = 1 ;
Rs = [0,1,2], R = 2.

Upvotes: 2

Related Questions