在 Prolog 中检索给定区间内的所有数字
我是 Prolog 世界的新手,我想编写一条返回特定范围内的所有元素的规则。
我打算做类似的事情
,例如:
foo(X, Low, High) :- X > Low, X < High.
当我输入 foo(X, 2, 5) 时,它应该返回 3,然后返回 4。
看来我的方法是错误的,我想知道哪种方法是正确的做吧。
I am new into the world of Prolog, and I would like to write a rule that return all the elements in a specific range.
I intend to do something like
Ex:
foo(X, Low, High) :- X > Low, X < High.
And when I type foo(X, 2, 5), it should return 3, and then 4.
It seems that my approach is wrong, and I would like to know which is the correct way to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当这样写时,Prolog 不知道你想要什么样的数字(以及你是否想要数字)。
实现这一点的一种方法是:
When written like that, Prolog doesn't know what kind of numbers do you want (and whether you even want numbers).
One way to implement this would be:
简单的答案:
Between/3 :通过
这种方式实现确切的行为有点微不足道。
您的方法不起作用的原因是
的定义:两个参数都应该实例化。所以,如果你想在不使用
Between/3 的情况下实现它,你应该像 svick 的建议那样做。
the easy answer:
between/3
:implementing the exact behaviour is kinda trivial this way.
the reason that your approach doesn't work is the definition of
</2
: both arguments should be instantiated. so, if you want to implement it without usingbetween/3
you should do something like svick's suggestion.使用 SWI-Prolog 和
library(clpfd)
,可以这样写Using SWI-Prolog and
library(clpfd)
, you can write你也可以这样做(几乎是 Between/3 的重新实现:
You could also do this (pretty much a reimplementatio of between/3: