比较序言中的事实时获得重复答案
使用 SWI-Prolog。我有一个排名列表:
rank(London, 3.5).
rank(New York, 3.5).
rank(Seattle, 2.3).
我正在尝试制定一条规则,打印/返回具有相同排名的任何事实。所以在这种情况下,它将与 London & 一起回来。纽约。
这是我到目前为止所想到的,唯一的问题是我得到的重复项(尽管它们对于当前规则来说非常有意义)。使用递归会有所帮助吗?
equal_rank(_):-
rank(U1, R1),
rank(U2, R2),
U1 \== U2,
R1 == R2,
print(R1), print(': '), print(U1), print(', '), print(U2), nl,
fail.
输出将是:
3.5: London, New York
3.5: New York, London
我只是不知道如何停止第二行。
Working with SWI-Prolog. I have a list of ranks say:
rank(London, 3.5).
rank(New York, 3.5).
rank(Seattle, 2.3).
And I am trying to get my head around making a rule that prints/returns any facts with the same rank. So in this case it would come back with London & New York.
Here's what I've come up with so far, the only problem is the duplicates I get with it (although they make perfect sense with the current rule). Would using recursion somehow help this?
equal_rank(_):-
rank(U1, R1),
rank(U2, R2),
U1 \== U2,
R1 == R2,
print(R1), print(': '), print(U1), print(', '), print(U2), nl,
fail.
The output would be:
3.5: London, New York
3.5: New York, London
I just can't figure out how to stop that second line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种简单的方法是用小于测试替换 U1 和 U2 之间的不相等测试:
这样给定的对仅出现一次。
A simple approach would be to replace the not-equal test between U1 and U2 with a less-than test:
This way a given pair only appears once.
我可能会选择使用 bagof/3 的方法,但我不知道这是否是解决您手头问题的首选或更合适的方法。根据您定义的事实,以下目标似乎会发出您想要的结果:
当然,它需要在格式化方面进行一些工作;将结果收集到列表中的想法可能对您有用,也可能没有用。哦,顺便说一句,我不确定城市名称是否需要是变量,所以正如你所看到的,我已经使用普通原子断言了
rank/2
事实。有关
bagof/3
的更多信息,您可以查阅 在线 SWI-Prolog 手册页 关于它。I would probably go for something that uses
bagof/3
, but I don't know whether that's the preferred or more apt approach for the problem you have at hand. With the facts you defined, the following goal seems to issue the result you want:It needs some work on formatting, of course; the idea of collecting results in a list may or may not be useful to you. Oh, and by the way, I was unsure about city names needing to be variables, so as you can see I have asserted
rank/2
facts using plain atoms.For a little bit of additional information on
bagof/3
, you may consult the online SWI-Prolog manual page about it.