chapter five

5 Monads as practical functionality providers

 

This chapter covers:

  • Pragmatic approach to monads and the functionality they provide
  • Accessing the 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, they promote coherent abstraction and guarantee 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 an approach of this chapter: we look at cases and apply monads to them. It makes sence to refresh an idea of abstracting computations from chapter 2 before reading this chapter.

5.1  Basic monads in use: Maybe, Reader, Writer

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

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

While the former two monads are extremely 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 very 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 dices

5.3  Other approaches to mutability

5.3.1  Mutable references in the IO monad

5.3.2  Mutable references in the ST monad

5.4  Summary