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
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.
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.
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: