liveBook · Manning

Ask

As explained in Learn Haskell by Example

ask retrieves the complete reader environment from a reader-like monadic computation.

ask reads the current read-only environment inside a Reader or ReaderT computation, avoiding explicit environment passing between actions. In ReaderT r m a, its type is Monad m => ReaderT r m r: it returns the complete environment without changing it. section 15.1.1

Reading application configuration

Define App a as ReaderT Config IO a, bind env <- ask, extract the source and destination paths, and use liftIO to print them. Running runReaderT example cfg supplies the configuration once and produces “src -> dst”. 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

A complete ReaderT example shows ask retrieving Config while IO performs the output. section 15.1.1

How Learn Haskell by Example covers it

How deep it goes
Defines ask's ReaderT type and demonstrates binding the environment, but defers implementation internals.
Examples
Uses integer Reader calculations and a file-synchronization Config containing source and destination paths.
What it assumes
Assumes basic monadic do notation and introduces Reader environments before combining them with IO through ReaderT.
What you can do after
Apply it via Control.Monad.Trans.Reader to retrieve configuration within ReaderT actions.
How it connects
Connects ask with Reader, ReaderT, monad transformers, IO, and liftIO.

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.