4 Immutable Values

 

Chapter 3 from Grokking Functional Programming by Michał Płachta

In this chapter:

  • mutability is dangerous
  • fighting mutability by working with copies
  • what is the shared mutable state?
  • fighting mutability by working with immutable values
  • using immutable APIs of String and List

Bad programmers worry about the code. Good programmers worry about data structures and their relationships.

— Linus Torvalds

3.1 The fuel for the engine

In the last chapter we met a pure function, which is going to be our best friend throughout the rest of the book. We introduced and briefly discussed some caveats regarding values that may change—mutable states. This chapter focuses on problems with mutable states and explains why pure functions can’t use them in majority of cases. We are going to learn about immutable values, which are used extensively in functional programming. The relation between a pure function and an immutable value is so strong, that we can define the functional programming using only those two concepts:

Functional Programming

is programming using pure functions that manipulate immutable values.


If pure functions make up the engine of the functional programs, immutable values are its fuel, oil and fumes:

3.2 Another case for immutability

3.3 Can you trust this function?

3.4 Mutability is dangerous

3.5 Functions that lie... again

3.6 Fighting mutability by working with copies

3.7 Coffee Break: getting burnt by mutability

3.8 Coffee Break Explained: getting burnt by mutability

3.9 Introducing shared mutable state

3.10 State’s impact on programming abilities

3.11 Dealing with the moving parts

3.12 Dealing with the moving parts using FP

3.13 Immutable values in Scala

3.14 Building our intuitions about immutability

3.15 Coffee Break: The Immutable String API

3.16 Coffee Break Explained: The Immutable String API

3.17 Hold on... isn’t this bad?

3.18 Purely functional approach to the shared mutable state

3.19 Practicing immutable slicing and appending

3.20 Summary

sitemap