Example of defining a custom aggregate function
The following example shows the definition of a custom aggregate function that returns the weighted standard deviation of the input values.
aggregate bounded wstddev( float x, float w ) returns float {
// 1st argument is the value, 2nd is the weight.
float s0;
float s1;
float s2;
action add( float x, float w ) {
if (w != 0.0) {
s0 := s0 + w;
s1 := s1 + w*x;
s2 := s2 + w*x*x;
}
}
action remove( float x, float w ) {
if (w != 0.0) {
s0 := s0 - w;
s1 := s1 - w*x;
s2 := s2 - w*x*x;
}
}
action value() returns float {
if (s0 != 0.0) { return ((s2 - s1*s1/s0)/s0).sqrt(); }
else { return float.NAN; }
}
}