6 Structuring programs with monad transformers

 

This chapter covers:

  • Using monad transformers to extend a monad functionality
  • Describing an application structure with monad stacks
  • Defining your own monad transformers
  • Overview of the most common monad transformers provided by the Haskell libraries

We’ve seen many monads already. You know that every monad specifies a way to combine two computations in sequence by implementing the >>= operator. You also know that in a monadic setting we have a result of a computation with some additional effects: computations may fail (as in the Maybe monad) or give an opportunity to communicate with the real world by doing input and otput (as in the IO monad), you may mutate state or consult an environment in some other effectful computations. There are many other monads you may not be aware of but you already know what all of them share in common.

In this chapter we’ll discuss one simple question: how to express computations that need to use more than one monad at the same time? We’ll start with exploring the problem: let’s take a task that can be solved in one monad, find some flaws in that solution, and try to fix them. In Haskell it is often the case that there is a monad for that. But we have a monad already so the problem now is how to add another monad to a solution. Let’s see.

6.1  The problem of combining monads: State + Maybe

 
 

6.1.1  Evaluating expressions in the reversed polish notation

 

6.1.2  Analyzing flaws

 
 
 

6.1.3  An attempt to fix the flaws: report Nothing in case of error

 
 
 
 

6.1.4  Introducing monad transformers and monad stacks

 
 
 
 

6.1.5  Hiding explicit Nothing manipulations with Alternative

 
 
 

6.2  IO-based monad transformer stacks

 
 
 

6.2.1  Describing monad stack: an application

 
 

6.2.2  Computing file space usage

 
 

6.2.3  Configuring and running an application

 
 
 

6.2.4  Extending functionality: file counter

 
 

6.2.5  Can we do it without RWST?

 

6.3  What is a monad transformer

 
 
 

6.3.1  Step 0: defining a type for a transformer

 
 
 
 

6.3.2  Step 1: turning a monad stack into a monad

 
 
 
 

6.3.3  Step 2: implementing the full monad stack functionality

 
 
 

6.3.4  Step 3: supplying additional functionality

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest