Building Out the Monad Transformer Library
In this chapter, we focused on two specific monad transformers: StateT and ExceptT . The transformers library provides several other commonly used monad transformers. One of the most common monad transformers is the ReaderT transformer. This monad transformer lets you write computations that have a read-only environment:
| | newtype ReaderT r m a = ReaderT {runReaderT :: r -> m a} |
The two basic operations for a ReaderT monad are ask , which fetches the value from the read-only environment, and local , which lets you run a ReaderT action with a modified local read-only environment. Their types are:
| | ask :: Monad m => ReaderT r m r |
| | local :: Monad m => (r -> r) -> ReaderT r m a -> ReaderT r m a |
In this exercise, write Functor , Applicative , Monad , MonadIO , and MonadTrans instances for ReaderT , and provide a definition for both ask and local . Once you have created a working definition of ReaderT , add a new class called MonadReader :
| | class Monad m => MonadReader r m | m -> r where |
| | ask :: m r |
| | local :: (r -> r) -> m a -> m a |
Next, finish writing the following instances:
| | instance Monad m => MonadReader r ( Reader . ReaderT r m) where |
| | instance MonadReader r m => MonadReader r ( ExceptT e m) where |
| | instance MonadReader r m => MonadReader r ( StateT s m) where |
A New FilePackParser
Refactor the FilePackParser application that you wrote earlier in this book to use the following monad:
| | newtype FilePackParser a = FilePackParser |
| | { runFilePackParser :: StateT Text ( ExceptT Text IO ) a } |
Copyright © 2023, The Pragmatic Bookshelf.