14 Local effects and mutable state

 

This chapter covers

  • Introducing mutable state
  • Discussing the ST monad
  • Providing a better definition of referential transparency

In the first chapter of this book, we introduced the concept of referential transparency, setting the premise for purely functional programming. We declared that pure functions can’t mutate data in place or interact with the external world. In chapter 13, we learned this isn’t exactly true; we can write purely functional and compositional programs that describe interactions with the outside world. These programs are unaware that they can be interpreted with an evaluator that has an effect on the world.

In this chapter, we’ll develop a more mature concept of referential transparency. We’ll consider the idea that effects can occur locally inside an expression and that we can guarantee no other part of the larger program can observe these effects occurring. We’ll also introduce the idea that expressions can be referentially transparent with regard to some programs and not others.

14.1 Purely functional mutable state

Up until this point, you may have had the impression that in purely functional programming you’re not allowed to use mutable state. But if we look carefully, there’s nothing about the definitions of referential transparency and purity that disallows mutation of local state. Let’s refer to our definitions from chapter 1.

14.2 A data type to enforce the scoping of side effects

14.2.1 A little language for scoped mutation

14.2.2 An algebra of mutable references

14.2.3 Running mutable state actions

14.2.4 Mutable arrays

14.2.5 A purely functional in-place quicksort

14.3 Purity is contextual

14.3.1 What counts as a side effect?

14.4 Conclusion

Summary

14.5 Exercise answers