madd a b = do aa <- a
bb <- b
return (aa + bb)
data Counter a = Counter a Int
deriving (Show,Eq)
instance Functor Counter where
fmap f (Counter a i) = Counter (f a) i
instance Applicative Counter where
pure x = Counter x 0
Counter f i <*> Counter x j = Counter (f x) (i + j)
instance Monad Counter where
return x = Counter x 0
Counter a i >>= f =
let Counter b j = f a
in Counter b (i + j + 1)
So suppose for this code one runs:
madd (Counter 10 43) (Counter 32 1)
and one gets Counter 42 46
.
I do not get how this produces this result. So madd
"calls" monad Counter
, then passes +
function to >>=
part of the monad instance. But then I find how the monad instance calls/passes functions/results very puzzling.
Can anyone explain in detail how intermediate calculations work?