Search code examples
listprologinsert-update

Prolog Create a List


I have to create list of n elements for example,

do_list(5,L1).

should return,

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

This is what I have, but it's not working.

do_list(X,L1):- X1 is X-1, do_list(X1,[X1|L1]).

do_list(0,[]).

Solution

  • If you want to create a list of consecutive numbers from 1 to N you can use builtin predicates findall/3 and between/3 this way:

    do_list(N, L):- 
      findall(Num, between(1, N, Num), L).
    
    ?- do_list(5,L).
    L = [1, 2, 3, 4, 5].
    

    SWI also has another builtin which does just that, numlist/3:

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