By recursion
let rec sumTotal list =
match list with
| [] -> 0 // empty list -> return 0
| head :: tail -> head + sumTotal tail
The above example says: "Look at the list
, is it empty? return 0. Otherwise it is a non-empty list. So it could be [1]
, [1; 2]
, [1; 2; 3] etc. If list
is [1] then bind the variable head
to 1
and tail
to []
then execute head + sumTotal tail
.
Example execution:
sumTotal [1; 2; 3]
// head -> 1, tail -> [2; 3]
1 + sumTotal [2; 3]
1 + (2 + sumTotal [3])
1 + (2 + (3 + sumTotal [])) // sumTotal [] is defined to be 0, recursion stops here
1 + (2 + (3 + 0)))
1 + (2 + 3)
1 + 5
6
A more general way to encapsulate the above pattern is by using functional folds! sumTotal
becomes this:
let sumTotal list = List.fold (+) 0 list