Created
June 10, 2013 20:51
-
-
Save egonSchiele/5752172 to your computer and use it in GitHub Desktop.
Reader monad example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Monad.Reader | |
hello :: Reader String String | |
hello = do | |
name <- ask | |
return ("hello, " ++ name ++ "!") | |
bye :: Reader String String | |
bye = do | |
name <- ask | |
return ("bye, " ++ name ++ "!") | |
convo :: Reader String String | |
convo = do | |
c1 <- hello | |
c2 <- bye | |
return $ c1 ++ c2 | |
main = print . runReader convo $ "adit" |
answered my own question:
convo = hello >>= \h -> (bye >>= \b -> return $ h ++ b)
so the reader makes sure hello
bye
and the return
ed functions are all called with the same input
alternatively with fmap (<$>):
convo = hello >>= \h -> (\b -> h ++ b) <$> bye
or with apply (<*>)
import Control.Monad.Reader
hello :: Reader String String
hello = asks $ \name -> ("hello, " ++ name ++ "!")
bye :: Reader String String
bye = asks $ \name -> ("bye, " ++ name ++ "!")
convo :: Reader String String
convo = asks (const (++)) <*> hello <*> bye
main = print . runReader convo $ "adit"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ok I see that shared data, but the readers are literally being unwrapped concatenated and then rewrapped... what about <$> and >>=?