## F# Seq.fold

A lot of the business code we tend to write deals with taking some collection and producing some fact about that collection. Examples include:

• Taking all the line items in a sales order and producing a total value of the order.
• Concatenating a set of order lines to create an order.

In F#, one can take a sequence of items and fold it to return another item representing some truth about that collection. This is done via the Seq.fold function. Typical invocation involves taking some collection, passing that collection via the pipeline operator, |>, to Seq.fold. Seq.fold then takes a function that has two values passed to it: an accumulator and the next value in the collection. Each value is folded into the accumulator in some fashion– if summing up numbers or concatenating strings, the accumulator is just another number or string. On each successive iteration, the return value appears as the accumulator to do more work. The accumulator can also be a different type from the list. Below, we have two examples:

• sum x calculates the sum of a sequence of numbers.
• concantenate x takes a sequence of objects and returns the result of concatenating all the string representations together. The example uses the characters ‘a’ to ‘z’.

1 #light

2

3 open System

4 let numbers =[1..100]

5 let letters=[‘a’..‘z’]

6

7 let sum x = x |> Seq.fold(fun acc a -> acc + a) 0

8 let concatenate x =

9     x |> Seq.fold(fun acc a -> String.Format("{0}{1}", acc, a)) ""

10

11 let doWork=

12     printfn("%d") (sum numbers)

13     printfn("%s") (concatenate letters)

This writes:

5050
abcdefghijklmnopqrstuvwxyz