序言。如何返回范围内的整数列表
我想返回给定输入的整数列表: rList :- (X,Y,[]) (1,4, N) 返回 N= [1,2,3,4]。 这也需要适用于负整数,反之亦然 输入 (4,-2, N) 返回 N= [4,3,2,1,0,-1,-2]。
到目前为止,我已经编写了开头的程序,但我被困住了。有人可以向我解释我应该如何继续吗?
rList(_ , _ ,[ ]).
rList(X, Y, [X|T]) :-
must_be(integer, X),
must_be(integer, Y),
X =< Y,
N is X + 1,
rList(N,Y,T).
返回:rList(1,4,N) N= [], [1], [1,2], [1,2,3], [1,2,3,4], false。此外,所有这些第一步不应因此而被退回。我只需要最后一个列表 ([1,2,3,4]) 作为输出。
I want to return a list of integers given an input:
rList :- (X,Y,[])
(1,4, N) returns N= [1,2,3,4].
This also needs to work for negative integers and for the other way around such that
the input (4,-2, N) returns N= [4,3,2,1,0,-1,-2].
So far i have programmed the beginning, but I am stuck. Can someone explain to me how I should continue?
rList(_ , _ ,[ ]).
rList(X, Y, [X|T]) :-
must_be(integer, X),
must_be(integer, Y),
X =< Y,
N is X + 1,
rList(N,Y,T).
this returns for: rList(1,4,N) N= [], [1], [1,2], [1,2,3], [1,2,3,4], false. Also all those first steps should not be given back as a result. I just need the last list ([1,2,3,4]) as an output.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为了性能,增量或减量决策应该一次,所以这里是:
swi-prolog 中的结果:
The increment-or-decrement decision should be made once, for performance, so here it is:
Result in swi-prolog:
一个可能的解决方案是:
示例:
A possible solution is:
Examples:
解决方案 1(常见解决方案):
解决方案 2(实现内置
Between
):解决方案 3(遵循您的解决方案):
--- 编辑 ---
谢谢@slago,我没有注意到这两个-way 要求,但它可以很容易实现:
另外,对于 rList:
Solution 1 (common solution):
Solution 2 (implement built-in
between
):Solution 3 (follow your solution):
--- Edit ---
Thanks @slago, I didn't notice the two-way requirement, but it can be easily implemented:
Also, for
rList
:只需一个简单的操作
就可以解决问题。如果你需要保护它,一个简单的装饰器就可以了:
Just a simple
should do the trick. If you need to guard it, a simple decorator will do: