6 Domain modeling with free monads

This chapter covers

  • Free monads and how to use them in domain modeling
  • How to apply the functor abstraction
  • Some advanced functional concepts

Imagine you’re building a robot from a bunch of preprogrammed modules. Each module can do something specific, like move something forward, turn on the lights, or make a sound. To make the robot do something interesting, you need to create a sequence of actions using these blocks. For different behaviors, you’d rearrange the sequence. Obviously, being able to create and arrange these sequences will make the robot easier to control.

That’s the basic idea behind a free monad. A free monad is a data structure that organizes domain-related actions into interpretable sequences (interpretable scenarios), making it possible to alter those sequences more easily as values. In this chapter, we’ll take a closer look at this concept from functional programming and see how free monads make domain modeling and eDSL design even more powerful and convenient. Free monads play the central role in the rest of the book, serving as functional interfaces that will enhance our programs with good design qualities, such as low coupling, proper subsystems design, and testability.

6.1 Introducing free monads

6.2 Free monads as a functional interface

6.2.1 Decoupling of computation and interpretation

6.2.2 The Free Monad pattern

6.2.3 Advantages and disadvantages

6.3 How free monads work

6.3.1 Wrapping languages into the free monad

6.3.2 The Free type

6.3.3 The functor instance

6.3.4 Learning the recursive free type

6.3.5 Interpretation of free monadic scripts

6.4 Free monadic eDSLs

6.4.1 Improving eDSLs with the free monad

6.4.2 Hierarchical free eDSLs

Summary