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?
You could simply use
forall/2
predicate to examine every element like:Now querying: