Prolog-从事实列表中获取set的最大值(使用失败谓词) [英] Prolog - getting a maximum value of set from a list of facts (using fail predicate)

查看:231
本文介绍了Prolog-从事实列表中获取set的最大值(使用失败谓词)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有如下事实列表:

Basically I have a list of facts like this:

set(x,2).
set(x,7).
set(x,10).
set(x,4).

我需要找到这个集合的最大元素.

I need to find the maximum element of this set.

输入:maximum(x, MaxElement)

输出:MaxElement = 10.

现在,这个想法本身并不复杂,我自己在网上看到了很多例子.问题是我需要使用 fail 谓词.

Now the idea itself isn't complicated and I saw many examples online myself. The problem is that I need to use the fail predicate.

这是我的主意(无效):

Here was my idea (which doesn't work):

maximum(Set, Element1):-
    set(Set,Element1),
    set(Set,Element2), 
    Element2 > Element1,
    fail.

maximum(Set, Element) :- set(Set, Element).

这里的想法是第一个规则查找集合中具有较大元素的每个元素.如果有更大的因素,我们将失败并停止.

The idea here was that the first rule looks for every element which has a bigger element in the set. If there is a bigger element we fail and stop.

然后最好是最大的(10),我们将不会失败并继续执行下一个规则,该规则只会看到它在集合中并返回true.

Then ideally for the biggest one (10), we would not fail and move on to the next rule which just sees that it is in the set and returns true.

但是这样,每个数字仍然会遵循第二条规则.另外,使用cut似乎无效.

But like this it still goes to the second rule with every number. Also using cut doesn't seem to work.

有什么想法的人吗?

推荐答案

您可以简单地使用forall/2谓词来检查每个元素,例如:

You could simply use forall/2 predicate to examine every element like:

maximum(Set, Element1):-
    set(Set,Element1),
    forall(set(Set,Y),(Y>Element1->fail;true)).

现在查询:

?-  maximum(x,X).
X = 10 ;
false.

这篇关于Prolog-从事实列表中获取set的最大值(使用失败谓词)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆