Prolog: list of numbers

14,310

Solution 1

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.

Solution 2

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.

Share:
14,310
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin 7 months

    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 = [].