Search code examples
prologvisual-prolog

Prolog. Does not create a list


I want to create a list consisting of N elements. I write the following code:

DOMAINS
    list = integer*
PREDICATES
    create(integer, integer, list)
CLAUSES
    create(_, 0, []).

    create(Start, End, [Start|T]):-
        Start < End + 1,!,
        Counter = Start + 1,
        create(Counter, End, T).
GOAL
    create(1, 5, L).

But it returns me No Solution.

On the other hand if I change the direction of my Counter like this:

DOMAINS
    list = integer*
PREDICATES
    create(integer,list)
CLAUSES
    create(0,[]).

    create(N,[N|T]):-
        N > 0,
        NN = N - 1,
        create(NN,T).
GOAL
    create(5,L).

It returns me 1 Solution: L=[5,4,3,2,1]. It's working good, but not in the order. What wrong in my first variant of code?


Solution

  • You need to make some adjustments to your program:

    1. The stop clause is never unified, because you don't decrement the End term.
    2. Counter need to be evaluated to the expression Start + 1, so use the is/2 operator.
    3. You don't need the cut on the second clause, but on the first one.

    Program:

    create(X, X, [X]):- !.
    create(Start, End, [Start|T]):-
            Start =\= End,
            Counter is Start + 1,
            create(Counter, End, T).
    

    Consult(You need the list to be instantiated, so use a variable instead of the empty list)

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