Question of a manual computation on Reader Monad.

Hi all, In order to improve my understanding of monad, I am trying to do some manual computation on "Reader Monad" but I got some problem. The computation is like this: --instance Monad (Reader e) where -- return a = Reader $ \e -> a -- (Reader r) >>= f = Reader $ \e -> f (r e) e runReader (do { b <- Reader $ show; return b } ) -- This is the initial expression, it should equals "show" runReader (Reader $ show >>= \b -> return b) -- remove do notion runReader (Reader $ \e -> return( show e ) e) -- apply the definition of ">>=" runReader (Reader $ \e -> (Reader $ \e1 -> show(e)) e) -- apply the definition of "return" But the last expression is incorrect, and I don't know how to go on. Could anyone explain this for me? Thanks in advance! Reference : http://www.haskell.org/all_about_monads/html/readermonad.html

Peter Cai:
Hi all,
In order to improve my understanding of monad, I am trying to do some manual computation on "Reader Monad" but I got some problem.
The computation is like this:
--instance Monad (Reader e) where -- return a = Reader $ \e -> a -- (Reader r) >>= f = Reader $ \e -> f (r e) e
This cannot work out because this definition is ill-typed, which you will notice if you try to compile it (or if you contemplate about what the type of (f (r e) e) is). Here is a way to define a reader monad: newtype Reader e a = Reader { runReader :: (e -> a) } instance Monad (Reader e) where return a = Reader $ \_ -> a Reader r >>= f = Reader $ \e -> runReader (f (r e)) e You can then do your calculation like this: Reader show >>= return = Reader $ \e -> runReader (return (show e)) e = Reader $ \e -> runReader (Reader (\_ -> show e)) e = Reader $ \e -> (\_ -> show e) e = Reader $ \e -> show e = Reader show; -- Note that, except for the use of “show” as a specific -- example, the above is equivalent to proving that the -- second monad law holds for (Reader e). runReader (Reader show >>= return) = runReader (Reader show) = show. Malte

一首诗 wrote:
runReader (do { b <- Reader $ show; return b } ) -- This is the initial expression, it should equals "show"
runReader (Reader $ show >>= \b -> return b) -- remove do notion
I'm not sure that's the right un-do-ization. It so happens that the exponent monad ((->) r) and the Reader monads are semantically identically. Is this a homework question? 一首诗 wrote:
runReader (Reader $ \e -> return( show e ) e) -- apply the definition of ">>="
runReader (Reader $ \e -> (Reader $ \e1 -> show(e)) e) -- apply the definition of "return"
But the last expression is incorrect, and I don't know how to go on.
-- View this message in context: http://www.nabble.com/Question-of-a-manual-computation-on-Reader-Monad.-tf43... Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.
participants (3)
-
Kim-Ee Yeoh
-
Malte Milatz
-
Peter Cai