7 Working with collections

 

This chapter covers

  • Higher-order functions
  • Functional collection pipelines
  • F# Collections
  • Aggregations

Until now, we’ve only really looked at individual items of data, also known as scalars. This chapter looks at how we work with multiple items of data at once. We do this all the time (e.g., working with a list of orders or customers, etc.). Collections are especially important in F# and functional programming languages in general because a lot of what we do involves thinking of things in terms of data transformations.

7.1 Higher-order functions

Before we dive into collections, there’s a prerequisite to understanding them known as higher-order functions (HOFs), which are one of the ways you compose code in F# (there are others that we’ll see toward the end of this book). These are functions that take another function as an argument. You will probably have seen this in languages that support even limited functional programming–style features.

One of the uses of HOFs is for implementing some common algorithm that operates over some varying logic. In the object-oriented world, you would probably use either the template or strategy design pattern. In the functional programming world, it’s fairly easy to achieve the same thing with functions. Here’s an example of a simple calculation function that logs its output to the console:

let executeCalculation a b =
    let answer = a + b
    printfn $"Adding {a} and {b} = {answer}"
    answer

7.2 Functional collection pipelines

7.2.1 Imperative and declarative pipelines

7.2.2 Debugging pipelines

7.2.3 Understanding the List module

7.2.4 Common List functions

7.2.5 Ranges, slices, and indexing

7.3 Other collection types

7.3.1 Arrays

7.3.2 Sequences

7.3.3 ResizeArray

7.3.4 Dictionary

7.3.5 Map