Chapter 5. More on Immutability

We have seen how important immutability is for FP. This chapter focuses on a number of techniques that help promote immutability. These include recursion, higher order functions, and the combination of monoids with higher order functions. We include in the chapter a new pattern, called Monoid and Fold, which represents many seemingly different but actually very similar types of functions. Let us start the chapter with a discussion of mutable and immutable variables.

Note

Immutability is a key property in functional code. The less mutable state a program has, the less the programmer has to keep in mind while writing the program. A large number of programmer errors come from the programmer not being able to keep a mass of changing detail in mind at once. Changing state causes complexity that we must track and manage.

Mutable and Immutable Variables

Almost all programming languages allow you to create a variable, set its value, and then change it at a later time. For an example of one that does not allow this, look at Haskell. A variable that can be modified after it has been set is called a mutable variable.

Note

In imperative and object-oriented programming, mutable variables are ubiquitous. As I have said, in FP, we avoid mutable variables.

Immutability is particularly valuable when dealing with concurrency and parallelism, which we will look at in the next chapter. For now, we will look more closely at the way immutability can be achieved. You ...

Get Learning Functional Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.