[Haskell-beginners] Reader and ReaderT

Alexey Shmalko rasen.dubi at gmail.com
Thu Oct 15 21:55:01 UTC 2015


Hi,

You could generalize first to ReaderT [String] a String, so that you
could use it as ReaderT [String] IO String. You don't need to change
the implementation - just change the type.

Hope this helps,
Alexey

On Fri, Oct 16, 2015 at 12:37 AM, Grzegorz Balcerek
<gbalcerek72 at gmail.com> wrote:
> Hi,
>
> 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
>
>
> Program2.hs:11:21:
>     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 ?
>
> Regards
> Grzegorz Balcerek
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners


More information about the Beginners mailing list