Community
Modules 24

Control.Monad.Reader

experimental
Computation type:
Computations which read values from a shared environment.
Binding strategy:
Monad values are functions from the environment to a value.

The bound function is applied to the bound value, and both have access to the shared environment.

Useful for:
Maintaining variable bindings, or other shared environment.
Zero and plus:
None.
Example type:
Reader [(String,Value)] a

The Reader monad (also called the Environment monad). Represents a computation, which can read values from a shared environment, pass values from function to function, and execute sub-computations in a modified environment. Using Reader monad for such computations is often clearer and easier than using the State monad.

Inspired by the paper Functional Programming with Overloading and Higher-Order Polymorphism, Mark P Jones (http://web.cecs.pdx.edu/~mpj/) Advanced School of Functional Programming, 1995.

MonadReader class

class Monad m => MonadReader r m

See examples in Control.Monad.Reader. Note, the partially applied function type (->) r is a simple reader monad. See the instance declaration below.

ask :: m r

Retrieves the monad environment.

local :: (r -> r) -> m a -> m a

Executes a computation in a modified environment.

Reader to run in the modified environment.

(r -> r)

The function to modify the environment.

reader :: (r -> a) -> m a

Retrieves a function of the current environment.

(r -> a)

The selector function to apply to the environment.

asks :: MonadReader r m => (r -> a) -> m a

Retrieves a function of the current environment.

(r -> a)

The selector function to apply to the environment.

The Reader monad

type Reader r = ReaderT r Identity

The parameterizable reader monad, which is non-strict.

Computations are functions of a shared environment.

The return function ignores the environment, while m >>= k passes the inherited environment to both subcomputations:

<<images/bind-ReaderT.svg>>

runReader :: Reader r a -> r -> a

Runs a Reader and extracts the final value from it. (The inverse of reader.)

A Reader to run.

r

An initial environment.

mapReader :: (a -> b) -> Reader r a -> Reader r b

Transform the value returned by a Reader.

  • runReader (mapReader f m) = f . runReader m

withReader :: (r' -> r) -> Reader r a -> Reader r' a

Execute a computation in a modified environment (a specialization of withReaderT).

  • runReader (withReader f m) = runReader m . f

Computation to run in the modified environment.

(r' -> r)

The function to modify the environment.

The ReaderT monad transformer

newtype ReaderT r m a

The reader monad transformer, which adds a read-only environment to the given monad.

The return function ignores the environment, while m >>= k passes the inherited environment to both subcomputations:

<<images/bind-ReaderT.svg>>

ReaderT r m is strict if and only if m is.

ReaderT :: r -> m a -> ReaderT r m a

mapReaderT :: (m a -> n b) -> ReaderT r m a -> ReaderT r n b

Transform the computation inside a ReaderT.

  • runReaderT (mapReaderT f m) = f . runReaderT m

withReaderT :: (r' -> r) -> ReaderT r m a -> ReaderT r' m a

Execute a computation in a modified environment (a more general version of local).

  • runReaderT (withReaderT f m) = runReaderT m . f

Computation to run in the modified environment.

(r' -> r)

The function to modify the environment.

module Control.Monad.Trans mtl-2.3.2 · 2 declarations

class (forall m. Monad m => Monad (t m)) => MonadTrans t

The class of monad transformers. For any monad m, the result t m should also be a monad, and lift should be a monad transformation from m to t m, i.e. it should satisfy the following laws:

  • lift . return = return

  • lift (m >>= f) = lift m >>= (lift . f)

Since 0.6.0.0 and for GHC 8.6 and later, the requirement that t m be a Monad is enforced by the implication constraint forall m. Monad m => Monad (t m) enabled by the QuantifiedConstraints extension.

Ambiguity error with GHC 9.0 to 9.2.2

These versions of GHC have a bug (https://gitlab.haskell.org/ghc/ghc/-/issues/20582) which causes constraints like

(MonadTrans t, forall m. Monad m => Monad (t m)) => ...

to be reported as ambiguous. For transformers 0.6 and later, this can be fixed by removing the second constraint, which is implied by the first.

lift :: (Monad m) => m a -> t m a

Lift a computation from the argument monad to the constructed monad.

Example 1: Simple Reader Usage

In this example the Reader monad provides access to variable bindings. Bindings are a Map of integer variables. The variable count contains number of variables in the bindings. You can see how to run a Reader monad and retrieve data from it with runReader, how to access the Reader data with ask and asks.

import           Control.Monad.Reader
import           Data.Map (Map)
import qualified Data.Map as Map

type Bindings = Map String Int

-- Returns True if the "count" variable contains correct bindings size.
isCountCorrect :: Bindings -> Bool
isCountCorrect bindings = runReader calc_isCountCorrect bindings

-- The Reader monad, which implements this complicated check.
calc_isCountCorrect :: Reader Bindings Bool
calc_isCountCorrect = do
   count <- asks (lookupVar "count")
   bindings <- ask
   return (count == (Map.size bindings))

-- The selector function to use with 'asks'.
-- Returns value of the variable with specified name.
lookupVar :: String -> Bindings -> Int
lookupVar name bindings = maybe 0 id (Map.lookup name bindings)

sampleBindings :: Bindings
sampleBindings = Map.fromList [("count", 3), ("1", 1), ("b", 2)]

main :: IO ()
main = do
   putStr $ "Count is correct for bindings " ++ (show sampleBindings) ++ ": "
   putStrLn $ show (isCountCorrect sampleBindings)

Example 2: Modifying Reader Content With local

Shows how to modify Reader content with local.

import Control.Monad.Reader

calculateContentLen :: Reader String Int
calculateContentLen = do
   content <- ask
   return (length content);

-- Calls calculateContentLen after adding a prefix to the Reader content.
calculateModifiedContentLen :: Reader String Int
calculateModifiedContentLen = local ("Prefix " ++) calculateContentLen

main :: IO ()
main = do
   let s = "12345";
   let modifiedLen = runReader calculateModifiedContentLen s
   let len = runReader calculateContentLen s
   putStrLn $ "Modified 's' length: " ++ (show modifiedLen)
   putStrLn $ "Original 's' length: " ++ (show len)

Example 3: ReaderT Monad Transformer

Now you are thinking: 'Wow, what a great monad! I wish I could use Reader functionality in MyFavoriteComplexMonad!'. Don't worry. This can be easily done with the ReaderT monad transformer. This example shows how to combine ReaderT with the IO monad.

import Control.Monad.Reader

-- The Reader/IO combined monad, where Reader stores a string.
printReaderContent :: ReaderT String IO ()
printReaderContent = do
   content <- ask
   liftIO $ putStrLn ("The Reader Content: " ++ content)

main :: IO ()
main = runReaderT printReaderContent "Some Content"
Maintainer
libraries@haskell.org
Portability
non-portable (multi-param classes, functional dependencies)
Copyright
(c) Andy Gill 2001, (c) Oregon Graduate Institute of Science and Technology 2001, (c) Jeff Newbern 2003-2007, (c) Andriy Palamarchuk 2007
License
BSD-style (see the file LICENSE)
Build record and source files

Community contribution. The service has not verified this documentation. The generator reported 6 diagnostics.

Target: Linux on x86-64. Some inferred types and resolved links are not available.

Generator: aihc-haddock-858b1951-web-1

Metadata snapshot: 032b29dc8ecd03eaae7b1a84a40ef8560125381762749b2f47333bc9a4f4bb8e

Open the dependency plan · Download the documentation model

Import a package

Enter a package name and an exact version from Hackage. The site contains imported versions only.