简体   繁体   中英

Prolog: Return a list of numbers from 0 to N given N

I'm studying Prolog, in particular I'm focused on list.

Given a number n , return a list of numbers from 0 to n .

As example, given 2 the output will be [0,1,2]

Here is my code:

num2list(0,[0]).
num2list(X,[H|T]) :- 
  H is X,
  N is X-1, 
  num2list(N,T).

the output for num2list(2,X) is X=[2,1,0].

Maybe the solution is stupid, but I can't find a way. I tried to make some modifications to my code, but I just get errors.

This program is mine and I don't want use standard predicates like "in" or something, because I don't know and I want to make a pure recursion.

So what is an easy way to do this?

I see it done this way in a book, and I want maintain this way.

You want a list with ascending order but the predicate definition is constructing it in descending order. There's more than one sensible solution for this problem, including using de facto standard predicates such as between/3 . A solution close to the one you're trying is to use an additional argument:

num2list(N, List) :-
    num2list(0, N, List).

num2list(N, N, [N]).
num2list(N0, N, [N0| List]) :-
    N0 < N,
    N1 is N0 + 1,
    num2list(N1, N, List).

Sample call:

?- num2list(2, L).
L = [0, 1, 2] ;
false.

An issue of this particular solution is the spurious choice-point as you can notice on the sample call. This issue is also present in your code. It can be easily solved with a less declarative solution by using a cut or an if-then-else construct.

A simple solution:

num2list(N,L):-findall(X,between(0,N,X),L).

findall puts all X s that satisfy the between to the list L .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM