excitedWithin
excitedWithin

Reputation: 61

Create a list from zero down to a negative number

I want to make a program in which the user will give a negative number and it will return a list starting from zero till that number. Here is a desired output example create(-5,L). L = [0,-1,-2,-3,-4,-5]

could you help me in any way, please?

Upvotes: 1

Views: 374

Answers (3)

CapelliC
CapelliC

Reputation: 60034

What you're after is not really a program, just an 'idiomatic' pattern:

?- findall(X, (between(0,5,T), X is -T), L).
L = [0, -1, -2, -3, -4, -5].

Note the parenthesis around the Goal. It's a compound one...

Another way:

?- numlist(-5,0,T), reverse(T,L).
...

Upvotes: 1

lurker
lurker

Reputation: 58304

I would break it up into two auxiliary predicates. The auxiliary predicate is helpful for building the list in the direction you desire.

create(N, L) :-
    N < 0,
    create_neg(N, 0, L).
create(N, L) :-
    N >= 0,
    create_pos(N, 0, L).

create_neg(N, N, [N]).
create_neg(N, A, [A|T]) :-
    A > N,
    A1 is A - 1,
    create_neg(N, A1, T).

create_pos(N, N, [N]).
create_pos(N, A, [A|T]) :-
    A < N,
    A1 is A + 1,
    create_pos(N, A1, T).

This will put them in the right order as well:

| ?- create(-5, L).

L = [0,-1,-2,-3,-4,-5] ? a

no
| ?- create(5, L).

L = [0,1,2,3,4,5] ? a

no
| ?- 

Upvotes: 1

coder
coder

Reputation: 12982

Since you provided your code (which as mentioned in comments would be better to appear in your question), one problem I think is that with X>0 and X<0 clauses-cases you will have infinite recursion, maybe it would be better to use abs/1:

create(0,[0]).
create(X,[X|T]):- Y is abs(X), Y > 0,
                  (X>0 -> N is X-1 ; N is X+1),
                  create(N,T).

Though still one problem:

?- create(-5,L).
L = [-5, -4, -3, -2, -1, 0] ;
false.

?- create(5,L).
L = [5, 4, 3, 2, 1, 0] ;
false.

The list is built reversed so you could reverse it at the end like:

create_list(N,L):- create(N,L1), reverse(L1, L).

And now:

?- create_list(5,L).
L = [0, 1, 2, 3, 4, 5] ;
false.

?- create_list(-5,L).
L = [0, -1, -2, -3, -4, -5] ;
false.

Upvotes: 0

Related Questions