Question

Define a Prolog predicate makelist/3 such that makelist(Start, End, List) is true if List is a list of all integers from the integer Start to the integer End. For example:

makelist(3, 7, [3, 4, 5, 6, 7]) should be true.

Can't understand why my code doesn't work

makelist(H, L, _) :-
    L is H+1.
makelist(H, L, List) :-
    append([], [H], List), H1 is H+1.
makelist(H1, L, List) :-
    append(List, [H1], List1), last(List1, R),
    R \= L+1, makelist(N, L, List1), N is H1+1.
Was it helpful?

Solution

You can simplify your code, let's take your predicate and examine what is what you really need to do:

% makelist(X,Y,L)

Since your recursive call is increasing by 1 the first parameter, let's call it X, then your base case would be when X is the same than Y:

makelist(X,X,[X]) .

and your recursive call: it will be when X is smaller than Y, you need to increase X and add the value to the list:

makelist(X,Y,[X|L]) :-  X < Y ,
            X1 is X + 1 ,
            makelist(X1, Y, L).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top