Collect all “minimum” solutions from a predicate
Given the following facts in a database: foo(a, 3). foo(b, 2). foo(c, 4). foo(d, 3). foo(e, 2). foo(f, 6). foo(g, 3). foo(h, 2). I want to collect all first arguments that have the smallest second argument, plus the value of the second argument. First try: find_min_1(Min, As) :- setof(B-A, foo(A, B), [Min-_|_]), findall(A, foo(A, Min), As). ?- find_min_1(Min, As). Min = 2, As = [b, e, h]. Instead of setof/3 , I could use aggregate/3 : find_min_2(Min, As) :- aggregate(min(B), A^foo(A, B), Min), findall(A, foo(A, Min), As). ?- find_min_2(Min, As). Min = 2, As = [b, e, h]. NB This only gives the