Prolog - getting a maximum value of set from a list of facts (using fail predicate)

时间秒杀一切 提交于 2019-12-11 01:27:04

问题


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.

Input: maximum(x, MaxElement)

Output: MaxElement = 10.

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.

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.

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

Any ideas guys?


回答1:


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)).

Now querying:

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


来源:https://stackoverflow.com/questions/40365709/prolog-getting-a-maximum-value-of-set-from-a-list-of-facts-using-fail-predica

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!