Aggregate Operators

Flora supports a number of aggregate operators. These operators allow you to perform a pre-defined operation on a set of values that satisfy some formula. They include:

  • count, the number of ways to satisfy a formula
  • min, the smallest number value that satisfies a formula
  • max, the largest number value that satisfies a formula
  • sum, the sum of number values that satisfy a formula
  • avg, the average of number values that satisfy a formula
  • setof, the set of values that satisfy a formula
  • bagof, the “bag” (multi-set, i.e. set allowing duplicates) of values that satisfy a formula

For example, count can be used to get the number of children of a person:

?person [ numberOfChildren -> ?num ] :-
  ?num = count{?x | ?person [ child -> ?x ]}.

In this case, we count the number of different values for ?x such that ?person [ child -> ?x ] is true. If person is instantiated, the result is the count of children for that person. If not instantiated, the result is the aggregate count of children for all persons. Either of the following will give the individual count for each person:

?person [ numberOfChildren -> ?num ] :-
  ?person : Person,
  ?num = count{?x | ?person [ child -> ?x ]}.
numberOfChildren(?person,?num) :-
  ?person : Person,
  ?num = count{?x | ?person [child -> ?x]}.

The syntax for the other aggregate operators is the same except for the operator name.

The setof and bagof operators are somewhat similar to the forall operator (see Quantifiers for forall).

Note that negation used inside an aggregate operator may not work properly, so it should be exercised with caution. More information on negation can be found in Negation.