sum and product
Given a container of numbers, of a type in the Num
type class, we can
compute their sum or product:
sum :: Num a => t a -> a
product :: Num a => t a -> a
These are just the generalizations of sum
and product
for lists to arbitrary
foldable containers:
GHCi
>>> sum Nothing
0
>>> sum (Just 1)
1
>>> product Nothing
1
>>> product (Just 5)
5
>>> sum tree
11
>>> product tree
30
For the empty container, sum
and product
return the unit elements of
addition and multiplication, which are 0 and 1.
As we discussed before, sum
and product
can be implemented via foldl
or,
in the interest of efficiency, its strict cousin foldl'
:
sum = foldl' (+) 0
product = foldl' (*) 1
The actual default implementations provided in the standard library use the
Sum
and Product
monoids, the strict version of foldMap
and a low-level
version of function composition:
sum = getSum #. foldMap' Sum
product = getProduct #. foldMap' Product
In spirit, these are the same as our implementations using foldl'
.