1
votes

First of all I have a doubt about the semantic of a program , for example :

length([],0).
length([_|L],N):-
    length(L,N0),
    N is N0 + 1.

The first instruction means the base case , or it has other meanings ?

I have to write a prolog program that, given a number, returns a list of numbers from 0 to the given number. For example, when the input is 5, the output is [0,1,2,3,4,5].

I'm looking for a solution of this problem but I do not know how to start.

1
Yes, the first rule is the base case. What have you tried for generating the list of numbers? - Daniel Lyons

1 Answers

1
votes

There is a predicate in SWI-Prologs library that does almost what you need to do. It is called numlist/3. You can use it with lower and upper boundary:

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

And here the implementation:

numlist(L, U, Ns) :-
    must_be(integer, L),
    must_be(integer, U),
    L =< U,
    numlist_(L, U, Ns).

numlist_(U, U, List) :-
    !,
    List = [U].
numlist_(L, U, [L|Ns]) :-
    L2 is L+1,
    numlist_(L2, U, Ns).

You can get rid of the upper half of this completely, and lose one argument (your Lower is just 1).

If you play with this a bit you should be able to figure it out.