I'm currently struggling with a new element of Haskell: Monads. Therefore I was introduced to this by an example of creating a (>>=)
operator that executes a function on a Maybe
type (taking its actual integer value as argument to it) only if it's not equal to Nothing
, and otherwise return Nothing
:
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>= _ = Nothing
(Just x) >>= f = f x
However, I'm not quite sure how this works with the following usage of it:
eval (Val n) = Just n
eval (Div x y) = eval x >>= (\n ->
eval y >>= (\m ->
safediv n m))
It seems to me that the (>>=)
operator simply takes one Maybe
value and a function that returns one, however in this example usage code it seems like it's taking 2 times a Maybe
value and once a function. I was told however that it evaluates x
, puts the result in n
, then evaluates y
, puts the result in y
, and then executes the safediv
function on both. Although I don't see how the (>>=)
operator plays its role here; How does this work?
You can read it like this:
when you want do
eval (Div x y)
theneval x
:Just n
(using the first >>=)n
and have a look ateval y
(using the first >>=)Just m
(second >>=)m
and do a (second >>=)savediv n m
to return it's result - you still have then
from your closure!.in ever other caes return
Nothing
So here the
(>>=)
just helps you to deconstruct.Maybe it's easier to read and understand in the
do
form:which is just syntactic sugar around
(>>=)
let's chase the cases:
1.eval x = Nothing
andeval y = Nothing
: 2.eval x = Nothing
andeval y = Just n
:which is just the same:
3.eval x = Just n
andeval y = Nothing
: 4.eval x = Just n
andeval y = Just m
:you have
from this we conclude that
eval
produces aMaybe
value. The second equation, let's rewrite it asi.e.
See? There is only one function involved in each
>>=
application. At the top, it'sg
. Butg
defines – and uses –h
, soh
's body has access both to its argumentm
and theg
's argument,n
.If
eval x
producedNothing
, theneval x >>= g
is justNothing
, immediately, according to the>>=
definition for theMaybe
types (Nothing >>= _ = Nothing
), and noeval y
will be attempted.But if it was
(Just ...)
then its value is just fed to the bound function (Just x >>= f = f x
).So if both
eval
s produceJust ...
values,safediv n m
is called inside the scope where both argumentsn
andm
are accessible. It's probably defined asand so
h :: m -> Maybe m
andg :: n -> Maybe n
and the types fit,as per the type of bind for the Maybe monad,
Let's do element chasing to illustrate how it works. If we have
Then we can break this down into
Now we need to take a detour to compute
eval (Div (Val 0) (Val 1))
...And now back to our original call to
eval
, substitutingJust 0
in: