[Haskell-beginners] Reader and ReaderT

Grzegorz Balcerek gbalcerek72 at gmail.com
Thu Oct 15 21:37:14 UTC 2015


I have the following program:

import Control.Monad.Reader

first :: Reader [String] String
first = do
   strings <- ask
   return $ if (null strings) then "empty" else head strings

printFirst :: ReaderT [String] IO ()
printFirst = do
   strings <- ask
   let theFirstString = runReader first strings
   liftIO $ putStrLn theFirstString

main = runReaderT printFirst ["first","second"]

It compiles and works. However, in the printFirst function I am 
explicitly using ask and I am calling runReader.
Can I somehow avoid doing that?
The following version of the printFirst function does not compile.

printFirst :: ReaderT [String] IO ()
printFirst = do
   theFirstString <- first
   liftIO $ putStrLn theFirstString

     Couldn't match type `Data.Functor.Identity.Identity' with `IO'
     Expected type: ReaderT [String] IO String
       Actual type: Reader [String] String
     In a stmt of a 'do' block: theFirstString <- first
     In the expression:
       do { theFirstString <- first;
            liftIO $ putStrLn theFirstString }

Can I somehow call first without using ask and runReader ?

Grzegorz Balcerek

More information about the Beginners mailing list