简单的演示

Reader monad 的一个关键部分是 askhttps://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Reader.html#v:ask) 函数,该函数是为说明而定义的用途:

import Control.Monad.Trans.Reader hiding (ask)
import Control.Monad.Trans

ask::Monad m => ReaderT r m r
ask = reader id

main::IO ()
main = do
  let f = (runReaderT $ readerExample) :: Integer -> IO String
  x <- f 100
  print x
  --
  let fIO = (runReaderT $ readerExampleIO) :: Integer -> IO String
  y <- fIO 200
  print y

readerExample::ReaderT Integer IO String
readerExample = do
  x <- ask
  return $ "The value is: " ++ show x

liftAnnotated::IO a -> ReaderT Integer IO a
liftAnnotated = lift

readerExampleIO::ReaderT Integer IO String
readerExampleIO = do
  x <- reader id
  lift $ print "Hello from within"
  liftAnnotated $ print "Hello from within..."
  return $ "The value is: " ++ show x

以上将打印出来:

"The value is: 100"
"Hello from within"
"Hello from within..."
"The value is: 200"