F# Folds Calculating the sum of all elements of a list


Example

To calculate the sum of terms (of type float, int or big integer) of a number list, it is preferable to use List.sum In other cases, List.fold is the function that is best suited to calculate such a sum.

  1. Sum of complex numbers

In this example, we declare a list of complex numbers and we calculate the sum of all terms in the list.

At the beginning of the program, add a reference to System.Numerics

open System.Numerics

To calculate the sum, we initialize the accumulator to the complex number 0.

let clist = [new Complex(1.0, 52.0); new Complex(2.0, -2.0); new Complex(0.0, 1.0)]

let sum = List.fold (+) (new Complex(0.0, 0.0)) clist

Result:

(3, 51)
  1. Sum of numbers of union type

Suppose that a list be composed of numbers of union (float or int) type and want to calculate the sum of these numbers.

Declare before the following number type:

type number = 
| Float of float
| Int of int

Calculate the sum of numbers of type number of a list:

let list = [Float(1.3); Int(2); Float(10.2)]

let sum = List.fold (
                         fun acc elem -> 
                                        match elem with
                                        | Float(elem) -> acc + elem
                                        | Int(elem) -> acc + float(elem)
                        ) 0.0 list

Result:

13.5

The first parameter of the function, which represents the accumulator is of type float and the second parameter, which represents an item in the list is of type number. But before we add, we need to use a pattern matching and cast to type float when elem is of type Int.