chapter six

6 Purely functional state

 

This chapter covers:

  • Writing pure stateful APIs by making state updates explicit
  • Identifying general repetition when dealing with pure state transitions
  • Using combinators to abstract over explicit state transitions
  • Combining both multiple and nested state actions
  • Introducing a general state action data type
  • Using an imperative style when dealing with state actions
  • Using the Arrow state action API

Working with program state is tricky, and even more so in the context of functional programming where we value principals such as immutability and the eradication of side effects. Mutating state comes at a huge cost, making programs difficult to reason about and maintain. Fortunately we have a design pattern at hand to deal with program state in a pure functional way. Applying this pattern allows us to deal with state in a deterministic fashion and subsequently allows us to reason about and test our programs with greater ease.

By viewing the program state as a transition or action that is passed along as context during a series of transformations, we can contain and localize the complexity that is usually associated with state machines. We can even take this a step further by hiding these state transitions altogether through the use of higher order combinator functions that pass state actions along implicitly in the background. A pattern begins to emerge as we combine these concepts of passing and hiding state transitions in the background.

6.1 Generating random numbers using side effects

6.2 Purely functional random number generation

6.3 Making stateful APIs pure

6.4 An implicit approach to passing state actions

6.4.1 More power by combining state actions

6.4.2 Recursive retries through nested state actions

6.4.3 Applying the combinator API to the initial example

6.5 A general state action data type

6.6 Purely functional imperative programming using Arrow

6.7 Conclusion

6.8 Summary