liveBook · Manning

ReaderT monad

As explained in Learn Haskell by Example

ReaderT is a Haskell monad transformer that adds access to a read-only environment to an underlying monad.

ReaderT is a Haskell monad transformer that adds read-only environment access to an underlying monad. ReaderT r m a stores an environment of type r, uses m for effects, and produces a result of type a. section 15.1.1

Use ask to query the environment without passing it from action to action. Define an application type such as App a = ReaderT Config IO a, then lift IO actions with liftIO. section 15.1.1

The main design choices are:

  • Choose the environment type, such as Config. section 15.1.1
  • Choose the underlying monad, such as IO, to retain its capabilities. section 15.1.1
  • Lift actions from the underlying monad into ReaderT with lift or liftIO. section 15.1.1

Configuration-driven application

type App a = ReaderT Config IO a. An action can read configFromPath and configToPath with ask, print the paths using liftIO, and run with runReaderT example cfg. section 15.1.1

ghci> import Control.Monad.Trans.Reader
ghci> type App a = ReaderT Config IO a
ghci> import Control.Monad.IO.Class (liftIO)
ghci> :{
ghci| example :: App ()
ghci| example = do
ghci|   env <- ask
ghci|   let toPath = configToPath env
ghci|       fromPath = configFromPath env
ghci|     in liftIO $ putStrLn (fromPath <> " -> " <> toPath)
ghci| :}
ghci> cfg = Config "src" "dst" Nothing Nothing Nothing
ghci> runReaderT example cfg
src -> dst

Browse the complete ReaderT Config IO example, including the application type, environment query, lifted output, configuration value, and execution. section 15.1.1

How Learn Haskell by Example covers it

How deep it goes
Explains the type parameters, ask, runReaderT, and lifting, but stops short of broader transformer composition details.
Examples
Uses a file-synchronization Config containing source and destination paths, then prints a configured path mapping.
What it assumes
Requires basic monad and IO concepts while teaching environment access and action lifting through a concrete application.
What you can do after
Build it from scratch by defining a ReaderT application, querying configuration, lifting IO, and running the action with an environment.
How it connects
Connects ReaderT with the Reader monad, monad transformers, IO, MonadIO, MonadTrans, StateT, WriterT, and RWST.

Also explained in

Compare how 2 books explain ReaderT monad →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.