Reputation: 48644
I'm trying to wrap my head around this following piece of code:
ex2 = do
a <- return 1
b <- Cont (\fred -> fred 10)
return $ a + b
ghci > runCont ex2 show
"11"
How is String "11" the output of the function ? I get that part that the show function converts the 10 to String, but then how does a + b
take place since String numerals can't sum up ?
Upvotes: 1
Views: 500
Reputation: 47382
The key is that a
and b
have type Int
, and the conversion to a String
with show
is only done after a
and b
are summed.
If you need further convincing, ask yourself if you have any problem with
runCont ex2 id
or
runCont ex2 (\a -> a * a)
If you need even more convincing, note that the type definition and monad instance are
data Cont r a = Cont { runCont :: (a -> r) -> r }
instance Monad (Cont r) where
return a = Cont ($a)
so you can squint a bit and convince yourself that your example is equivalent to
ex = do
a <- return 1
b <- return 10
return (a + b)
which is just
ex = return (1 + 10)
Upvotes: 3