James
James

Reputation: 51

Prolog: list of numbers

How can I generate a list of numbers from 1 to N, where N >= 0?

Predicate: numbers(N, L).

?-­ numbers(5,X).

X = [1, 2, 3, 4, 5].

?­- numbers(0,X).

X = [].

Upvotes: 3

Views: 15742

Answers (2)

DaveEdelstein
DaveEdelstein

Reputation: 1256

You can use between to generate integers between to endpoints and then findall to collect them together. Try this predicate -

numbers(Count, List) :-
    findall(N, between(1,Count,N), List).

If you give Count anything <=0, between fails and this predicate will generate the empty list.

Upvotes: 6

Kaarel
Kaarel

Reputation: 10672

Use the built-in numlist/3:

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

?- numlist(1, 0, L).
false.

In SWI-Prolog you can use listing(numlist) to see how it has been implemented.

Note that numlist/3 will never generate an empty list. If you want that, then you need to write a simple wrapper that maps failure to an empty list.

Upvotes: 17

Related Questions