6 Patterns in functional programming

 

This chapter covers

  • The core functions: Return, Map, Bind, Where, and ForEach
  • Introducing functors and monads
  • Working at different levels of abstraction

A pattern is a solution that can be applied to solve a variety of problems. The patterns we’ll discuss in this chapter are simply functions: functions that are so ubiquitous when coding functionally that they can be seen as the core functions of FP.

You’re probably familiar with some of these functions like Where and Select (which is equivalent to Map), having used them with IEnumerable. But you’ll see that the same operations can be applied to other structures, hence establishing a pattern. I’ll illustrate this with Option in this chapter; other structures will follow in coming chapters.

As usual, I suggest you type along in the REPL and see how these core functions can be used. (You’ll need to import the LaYumba.Functional library as shown in the sidebar “Using the LaYumba.Functional library in the REPL” in chapter 5.)

6.1 Applying a function to a structure’s inner values

The first core function we’ll look at is Map. It takes a structure and a function and applies the function to the inner value(s) of the structure.1 Let’s start with the familiar case in which the structure in question is an IEnumerable.

6.1.1 Mapping a function onto a sequence

An implementation of Map for IEnumerable can be written as follows.

6.1.2 Mapping a function onto an Option

6.1.3 How Option raises the level of abstraction

6.1.4 Introducing functors

6.2 Performing side effects with ForEach

6.3 Chaining functions with Bind

6.3.1 Combining Option-returning functions