Monads
Let’s say that there is a function called getHalf
.
-- it halfs when even number is given
getHalf x =
if even x
then Just (x `div` 2)
else Nothing
This function does not work if we feed wrapped values, for example, Just 3
. To solve it, we should use bind(>>=)
operator.
> Just 5 >>= half
Nothing
> Just 10 >>= half
Just 5
Monad
is a typeclass.
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
And Maybe
is a Monad
.
instance Monad Maybe where
Nothing >>= func = Nothing
Just val >>= func = func val
Maybe
is a Functor
and also a Monad
!