7 Stateful applications

This chapter covers

  • Organizing stateful functional applications
  • Creating pure and impure states
  • Using state monads

Some people argue against functional programming by saying that it doesn’t work for real tasks because it lacks mutable variables. There are no mutable variables, and therefore, no state can change, so interaction with the program is impossible. You might even be hearing that a functional program is really a math formula without effects, and consequently, it doesn’t work with memory, network, standard input and output, and whatever else the impure world has. But when it does, it’s not functional programming anymore. There are even more emotional opinions and questions. For example, “Is it cheating in Haskell when an IO monad just masks the imperative paradigm?” The use of impure code in Haskell’s IO monad may even lead to questioning how it is functional when it’s clearly imperative.

Functional programming doesn’t mean there should be no state or side effects. In fact, functional programming is friendly to these concepts, but it does the job differently, preventing state and side effects from vandalizing our code.

7.1 Stateful functional programming

7.1.1 Simple stateful application

7.1.2 Purity, layering, state, and design

7.2 State-handling approaches

7.2.1 Argument-passing state

7.2.2 Pure state with the state monad

7.2.3 Bringing pure state into your monadic eDSLs

7.2.4 Impure mutable state

Summary