Chapter 12. Handling state mutation in a functional way
This chapter covers
- Creating a functional random number generator
- Designing a generic API for handling state mutation
- Handling and composing state operations
- Using recursive state operations
- Generic state handling
- Building a state machine
In this chapter, you’ll learn how to handle state in a purely functional way. In the previous chapters, state mutation was avoided as much as possible, and you might have come to believe that state mutation is incompatible with functional programming. This isn’t true. In functional programming, it’s perfectly possible to handle state mutation. The only difference from what you may be used to is that you have to handle state mutation functionally, which means without resorting to side effects.
For a programmer, there are many reasons for handling state mutations. One of the simplest examples is the random number generator. A random number generator is a component with a method that returns a random number. If the random number generator had no state (which means, in reality, no changing state), it would always return the same number. This is not what you expect.
On the other hand, because I’ve said many times in the previous chapters that a function, given the same argument, should return the same value, it might be difficult to imagine how such a generator would work.