Richard
Richard

Reputation: 1117

Prolog returning only the max value from all iterations

I have a method that returns me a number on all iterations, but now I need to returns only the max value from all of the iterations that were done.

find_max(X, Y):-
    find_number(X, Y).

So the find_number() returns only 1 number and some text alongside it. So for example if I were to ran it I would get this output:

X = 1, Y = me;
X = 5, Y = you;
X = 6, Y = he;

And the only output I need to return is the X = 6, Y = he;.
I am using SWI-Prolog.

Upvotes: 1

Views: 142

Answers (2)

Paulo Moura
Paulo Moura

Reputation: 18683

A more portable alternative to the library(aggregate) posted by Willem, as the library is only available in a few Prolog systems, is:

find_max_alt(Xm, Ym) :-
    setof(max(X, Y), find_number(X, Y), Solutions),
    reverse(Solutions, [max(Xm, Ym)| _]).

This solution also appears to required a smaller number of inferences. Using the data in the question, we get:

?- time(find_max(Xm, Ym)).
% 40 inferences, 0.000 CPU in 0.000 seconds (83% CPU, 800000 Lips)
Xm = 6,
Ym = he.

Versus:

?- time(find_max_alt(Xm, Ym)).
% 25 inferences, 0.000 CPU in 0.000 seconds (76% CPU, 675676 Lips)
Xm = 6,
Ym = he.

The setof/3 predicate is a standard predicate. The reverse/2 predicate is a common list predicate (and much simpler to define than the predicates in the aggregate library.

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477284

You can use the aggregate library for that:

:- use_module(library(aggregate)).

find_max(Xm, Ym):-
    aggregate(max(X, Y), find_number(X, Y), max(Xm, Ym)).

Upvotes: 1

Related Questions