Prolog - getting a maximum value of set from a lis

2019-07-18 04:25发布

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?

标签: prolog set max
1条回答
\"骚年 ilove
2楼-- · 2019-07-18 04:43

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.
查看更多
登录 后发表回答