I have a list of facts like this:
set(h, 3).
set(h, 6).
set(h, 12).
set(h, 1).
set(h, 7).
I need to find the maximum value of set h and the query needs to look like this:
?- maximum(h, Max).
Max = 12.
Now there are many ways to do this, obviously. But currently I'm looking for a way to do it with a dynamic predicate and also a fail predicate. I might have to use repeat I guess? Unfortunately both the repeat and dynamic predicate seem confusing to me.
I was thinking something like this:
set(h, 3).
set(h, 6).
set(h, 12).
set(h, 1).
set(h, 7).
:- dynamic current_max/1.
assert(current_max(0)).
maximum(Set, Element):-
repeat,
set(Set,Element),
current_max(Max),
(Max > Element,
fail);
(Element > Max,
retract(current_max(Max)),
assert(current_max(Element)),
fail).
maximum(_, Max):-
current_max(Max).
One of the issues I see myself is that the repeat cycle doesn't stop. If I would somehow know that it was the last element of the set I could probably use cut, but I'm not sure how.