Lesson 18. Folding your way to success

 

The preceding few lessons covered the main collection types and how to use them. Here we’ll round off with a few scenarios describing how collections can be used in interesting ways to achieve outputs and transformations that you might not think possible through folding. You’ll look at

  • Understanding aggregations and accumulation
  • Avoiding mutation through fold
  • Building rules engines and functional chains

18.1. Understanding aggregations and accumulators

You’re likely already familiar with some of the aggregation functions in LINQ or F# collections, such as Sum, Average, Min, Max, and Count (see figure 18.1). All of these have a common signature: they take in a sequence of elements of type T and return a single object of type U.

Figure 18.1. High-level visualization of aggregation

You can view this in terms of F# types as follows.

Listing 18.1. Example aggregation signatures
type Sum       = int   seq -> int             #1
type Average   = float seq -> float
type Count<'T> = 'T    seq -> int

As you can see, the Sum, Average, and Count functions all share a common theme: they take a collection of things and return a single other thing.

18.1.1. Creating your first aggregation function

Let’s look at how to implement the generic Sum aggregation; for example, calculating the sum of the numbers 1 to 5, or the total value of three customers, or the total cost of 10 orders. Performing any aggregation, or fold, generally requires three things:

18.2. Saying hello to fold

18.3. Composing functions with fold

Summary