Haskell MTL Idea
MTL is a library of typeclasses for shared monad operations. The same operation names work across many different monad stacks.
Ask reads the environment
The Reader operation ask returns the environment. Doubling it gives 42.
import Control.Monad.Reader
main :: IO ()
main = print (runReader (fmap (* 2) ask) 21)Modify changes the state
The State operation modify changes the stored value. Adding 5 to 10 gives 15.
import Control.Monad.State
main :: IO ()
main = print (execState (modify (+ 5)) 10)ThrowError reports a failure
The Error operation throwError stops a computation with a failure value. The result shows that failure.
import Control.Monad.Except
main :: IO ()
main = print (runExcept (throwError "bad" :: Except String Int))Example
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Except
main :: IO ()
main = do
print (runReader (fmap (* 2) ask) 21)
print (execState (modify (+ 5)) 10)
print (runExcept (throwError "bad" :: Except String Int))Key points
- Classes: MTL provides typeclasses instead of only concrete transformers.
- Reader operations: ask reads a shared environment value.
- State operations: get reads a changeable state value.
- Error operations: throwError reports a failure value.
- Reuse: the same code can run in a small stack or a large stack.
In this example, the Reader line doubles 21 to give 42, the State line adds 5 to 10 to give 15, and the Error line reports the failure value bad.
Note
MTL does not replace transformers, it gives shared names for their operations.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does MTL mainly provide for monad stacks?