How do I create a list with elements from 1 to N in prolog

LuThe Dog :

I've tried to create a program that makes a list with elements from 1 to N.

increasing(L, N):-
   increasing(L, N, 1).

increasing([X|L], N, X):-
   X =< N,
   X1 is X + 1,
   increasing(L, N, X1).

But for some reason it doesn't work

Willem Van Onsem :

The problem is that eventually, you will make a call to increasing/3 where X <= N is not satisfied, and then that predicate will fail, and thus "unwind" the entire call stack.

You thus need to make a predicate that will succeed if X > N, for example:

increasing(L, N):-
    increasing(L, N, 1).

increasing([], N, X) :-
    X > N,
    !.
increasing([X|L], N, X):-
    X =< N,
    X1 is X + 1,
    increasing(L, N, X1).

For example:

?- increasing(L, 5).
L = [1, 2, 3, 4, 5].

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=32900&siteId=1