5 Monads as practical functionality providers

 

This chapter covers

  • A pragmatic approach to monads and the functionality they provide
  • Accessing configuration, writing logs, and maintaining state with monads
  • Exploiting various approaches to mutability in the IO and ST monads

Monads can be seen and taught from many perspectives. The mathematics behind them is just one perspective, and we’ll ignore it by focusing on the functionality monads provide. Monads can simplify our code by promoting coherent abstraction and guarantees of the uniformity of the code. In this chapter, we’ll talk about using monads in practice. We’ll see how they help us to implement difficult algorithms clearly and correctly and to write short and concise code while maintaining readability and ease of support.

This is the approach of this chapter: we’ll look at cases and apply monads to them. It makes sense to refresh the idea of abstracting computations from chapter 2 before reading this chapter.

5.1 Basic monads in use: Maybe, Reader, Writer

In this section, we’ll focus on the following three monads:

  • The Maybe monad
  • The Reader monad
  • The Writer monad

Although the former two monads are often used in practice, the latter one is less used due to memory usage issues (basically, it is too easy to introduce space leaks with it). Nevertheless, all of them are useful to understand the pragmatics behind monads in general.

5.1.1 Maybe monad as a line saver

5.1.2 Carrying configuration all over the program with Reader

5.1.3 Writing logs via Writer

5.2 Maintaining state via the State monad

5.2.1 Basic examples with the State monad

5.2.2 Parsing arithmetic expressions with State

5.2.3 RWS monad to rule them all: The game of dice

5.3 Other approaches to mutability

5.3.1 Mutable references in the IO monad

5.3.2 Mutable references in the ST monad