Idiom # 54: Compute sum of integers
Code
The simplest way is using the generic feature sum
that can be
applied to all numeric types.
Using fold
shows a more generic way: fold
is the
feature of choice to join elements of a set into a value of the element type.
For type i32
, such operations are defined in the unit type returned
by feature i32
. To build the sum, i32.sum
is the
operation to use.
Mathematically speaking, such an operation is called a monoid. This is
why the type of the argument of fold
is Monoid
, while
the operations declared for i32
inherit from Monoid
.