Reputation: 184
I'm try to make a list of the values n,n+1,...2*n-1
for example if I have n=4 ==> [4,5,6,7]
I have managed to write this code but it shows the list of first n elements. Can you help me modify it?
create(N,L):-
create_list(N,[],L).
create_list(0,L,L).
create_list(N,R,L):-
N>0,
N1=N-1,
create_list(N1,[N|R],L).
Upvotes: 0
Views: 1345
Reputation: 18726
Here's how you could write a logically pure version of create/2
based on list_from_to/3
, defined in my answer to question "Fill list in SWI-Prolog":
create(From,Zs):-
To #= 2*From-1,
list_from_to(Zs,From,To).
Here the query you had in your question:
?- create(4,Zs).
Zs = [4,5,6,7] ;
false.
As create/2
is pure, it is versatile and can also be used in different ways:
?- create(N,[4,5,6,7]).
N = 4.
?- create(N,[4,_,_,_]).
N = 4.
Upvotes: 1
Reputation: 60014
You're doing 'in reverse', in a certain sense. Try
create(N,L):-
M is 2*N,
create_list(N,M,L).
create_list(N,M,[N|R]):-
N < M,
N1 = N+1, % note: check if your Prolog accepts is/2 instead
create_list(N1,M,R).
create_list(M,M,[]).
Upvotes: 0