Module aggregate

The aggregate predicates take a set of solutions and compute an aggregate on it. The predicate aggregate_all/3 aggregates the solution that is produced by findall/3. The predicate aggregate/3 respectively sys_collect/3 aggregates the solutions that are produced by bagof/3 respectively sys_heapof/3.

Examples:
?- [user].
p(4,5).
p(1,2).
p(1,3).

Yes
?- aggregate((sum(X),count),p(Y,X),R).
Y = 4,
R = (5,1) ;
Y = 1,
R = (5,2)

The implementation of aggregate_all/3 takes advantage of pivots introduced in the module sequence. The other aggregate predicates take advantage of a map from variant terms to pivots. The memory usage is therefore proportional to the number of variant terms.

The following aggregate predicates are provided:

aggregate_all(A, G, S):
The predicates aggregates the aggregate A for the solutions of G and unifies the result with S. The following aggregates are recognized.
count: The result is the number of solutions.
sum(X): The result is the sum of the X values.
mul(X): The result is the product of the X values.
min(X): The result is the minimum of the X values.
max(X): The result is the maximum of the X values.
(A,B): The result is the pairing of the aggregate A and B.
nil: The result is always nil.
first(C,X): The result is the C first of the X values.
last(C,X): The result is the C last of the X values.
reduce(I,A,X): The result is the I and A reduct of the X values.
aggregate(A, X1^…^Xn^G, S):
The predicates aggregates the aggregate A for the solutions of G and unifies the result with S. The result is sorted by the witnesses.
sys_collect(A, X1^…^Xn^G, S):
The predicates aggregates the aggregate A for the solutions of G and unifies the result with S. The result is grouped by the witnesses.

Comments