It's tricky, but important, to decide correctly what aggregate functions should do when passed the empty set.
Sometimes it's 'intuitively obvious': What is the SUM of no elements? Zero, I'm sure everyone would readily say.
Sometimes it's less so: What is the PRODUCT of no elements? Those with some mathematical training will quickly say "one", but this is not at all obvious.
Then you get to MIN and MAX and wow! How did we get those infinities?
One way to decide what an aggregate function should do here is consider what behaviours we want to remain consistent, even with empty sets. For example, suppose we have these non-empty sets:
A = { 1, 2, 3 }
B = { 4, 5 }
Now, it's true here, and indeed for any non-empty sets, that
SUM(A ∪ B) = SUM({SUM(A), SUM(B)})
15 = 6 + 9
PRODUCT(A ∪ B) = PRODUCT({ PRODUCT(A), PRODUCT(B) })
120 = 6 * 20
MIN(A ∪ B) = MIN({ MIN(A), MIN(B) })
1 = MIN(1, 4)
Wouldn't it be nice, say the mathematicians, if these properties remain true even when one or both of the sets are empty? It surely would.
And it's maintaining this behaviour that decides what value we assign to SOME_AGGREGATE_FUNCTION(∅)
:
In order for
SUM(A ∪ B) = SUM({ SUM(A), SUM(B) })
to remain true when A
is empty and B
is not, we must have SUM(∅) = 0
In order for
PRODUCT(A ∪ B) = PRODUCT({ PRODUCT(A), PRODUCT(B) })
to remain true when A
is empty and B
is not, we must have PRODUCT(∅) = 1
And finally:
In order for
MIN(A ∪ B) = MIN({ MIN(A), MIN(B) })
to remain true when A
is empty and B
is not, we need MIN(∅)
to be a value which is guaranteed to be greater than any possible value in B, so that it doesn't 'interfere with' the result of MIN(B)
. And we get our answer: MIN(∅) = +∞
Math.min/max
doesn't work on arrays.-2
and6
? They should beNaN
Math.Min
orMath.Max
without any parameters?