在序言中创建两个数字范围的列表

时间:2018-07-21 10:41:58

标签: prolog

我要建立两个给定数字范围内的数字列表。

例如:betweenRange(1,5,X)

将给出答案:X=[1,2,3,4,5]

知道怎么做吗?

我尝试过类似的事情:

elementsBetween(N1, N2, [N1|_]):-
   N2 =:= N1.
elementsBetween(N1, N2, List):-
   N2 > N1, N2New is N2-1, 
   elementsBetween(N1, N2New, [N2|List]).

但它不起作用,递归后回溯有些问题。

1 个答案:

答案 0 :(得分:-1)

betweenToList(X,X,[X]) :- !.
betweenToList(X,Y,[X|Xs]) :-
    X =< Y,
    Z is X+1,
    betweenToList(Z,Y,Xs).

输出:

?- betweenToList(1,5,X).
X = [1, 2, 3, 4, 5].

?- betweenToList(1,2,X).
X = [1, 2].

?- betweenToList(1,8,X).
X = [1, 2, 3, 4, 5, 6, 7, 8].

?- betweenToList(1,1,X).
X = [1].

?- betweenToList(1,0,X).
false.

通过减少Y可以实现相同的逻辑,您可以使用reverse/2(易于实现):

betweenDecYAux(X,X,[X]) :- !.
betweenDecYAux(X,Y,[Y|Ys]) :-
    X =< Y,
    Z is Y-1,
    betweenDecYAux(X,Z,Ys).

betweenDecY(X,Y,R) :-
    betweenDecYAux(X,Y,L),
    reverse(L, R). % reverse [c,b,a] to [a,b,c]

输出:

?- betweenDecY(1,6,X).
X = [1, 2, 3, 4, 5, 6].

?- betweenDecY(2,8,X).
X = [2, 3, 4, 5, 6, 7, 8].

?- betweenDecY(1,0,X).
false.