The aggregate predicates take a set of solutions and compute an
aggregate on it. The predi-cate aggregate_all/3 aggregates the
solution that is produced by findall/3. The predicate ag-gregate/3
respectively aggregate/4 aggregates the solutions that are
produced by bagof/3 respectively bagof/4.

?- [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):****aggregate_all(A, G, S, O):**- The predicates aggregates the aggregate A for the solutions of G and unifies the result with S. The quaternary predicate takes additional sort options as argument.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.

The sort options are the same as for compare/4 and friends. Except aggregates, also recognize the following sort option additions:

eager(E): Determine the aggregation method.

The allowed eager values are "false" and "true". The default value is "false".

**aggregate(A, X**_{1}^…^X_{n}^G, S):**aggregate(A, X**_{1}^…^X_{n}^G, S, O):- The predicates aggregates the aggregate A for the solutions of G and unifies the result with S. The result is sorted by the witnesses. The quaternary predicate takes additional sort options as argument.