我的目标是取X和Y之间的数字并产生Z.
num_between(3,6, All)
例如,如果X为3且Y为6,则Z为X和Y之间的数字列表。 num_between(3,6,[3,4,5,6])
之类的内容应评估为true
。这是我到目前为止所做的:
num_between(0,0, []).
num_between(X,Y, All) :-
increase(X, New) , % increase number X++
\+(X = Y) , % check if X is not equal to Y
num_between(New,Y,[All|X]) . % requestion ???
increase(F,N) :- N is F+1 .
increase/1
正在运行并返回所需的数字,但是
当递归遍历num_between/3
时,它会熄灭:X为6然后它按我的意愿失败,
但我无法保留数字或返回它们。全部= [3,4,5,6]。
全部=全部+ F.任何人都可以帮忙。
答案 0 :(得分:3)
您的基本子句不正确:因为您永远不会减少X
或Y
,所以它们永远不会为零(除非Y
从零开始,X
从非正值)。基本子句应如下所示:
num_between(X, Y, []) :- X > Y.
这可以确保当用户输入无效"后退"范围(例如,从6到3)。
现在转到主要条款:您需要做的就是检查范围是否有效,获取下一个值,并进行递归调用,如下所示:
num_between(X, Y, [X|Tail]) :-
X =< Y,
Next is X + 1,
num_between(Next, Y, Tail).
您的原始代码在构建列表时出错 - 它尝试使用X
作为&#34;尾部&#34;列表,这是不正确的:
num_between(New,Y,[All|X]).
你传递All
,即#34;扩展&#34;之后的结果,通过递归调用链。它应该是另一种方式 - 您需要传入Tail
来收集结果,然后在递归调用结束时将X
预先挂起。
答案 1 :(得分:1)
您必须更改基本案例和递归子句:
num_between(X, X, [X]).
num_between(X, Y, [X|L]):-
X < Y,
increase(X, New),
num_between(New, Y, L).
第一个子句是基本情况,它表明X和X之间的数字只是[X]
。
recursive子句指出小于X
的数字Y
应该在输出列表中有它(因此头部的第三个参数中的[X|L]
),然后它增加了值(我只是使用你的助手程序)并且现在以第一个参数的New
值递归调用自身。
答案 2 :(得分:0)
我会按以下方式写这个:
numbers_between( X , X , [X] ) . % if X and Y have converged, we have the empty list
numbers_between( X , Y , [X|Zs] ) :- % otherwise, add X to the result list
X < Y , % - assuming X is less than Y
X1 is X+1 , % - increment X
numbers_between(X1,Y,Zs) % - recurse down
. %
numbers_between( X , Y , [X|Zs] ) :- % otherwise, add X to the result list
X > Y , % - assuming X > Y
X1 is X-1 , % - decrement X
numbers_between(X1,Y,Zs) % - recurse down
. %