Maybe monad usage example

haskell, monads

Solution

For `Maybe` monad bind function (`>>=`) looks like that:

(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b

So, let's define some `Maybe a` value:

> let a = Just 1
a :: Maybe Integer

And `:: a -> Maybe b` function:

> let f = \x -> Just (x+1)
f :: Integer -> Maybe Integer

Now we can use bind like infix operator:

> a >>= f
Just 2
it :: Maybe Integer

Another example of really `a -> Maybe b` function could be:

let h :: Integer -> Maybe String; h = return . show . (+1)
h :: Integer -> Maybe String

So `h` increment integer number, convert it to string and make a `Maybe` value with `return` function.

> a >>= h
Just "2"

Problem

I'm trying to learn Haskell but I'm having problem in monad usage. I imported the module `Data.Maybe`. But I don't know how to use the `>>=` operator. Given `(>>=) :: Monad m => m a -> (a -> m b) -> m b` I cannot understand how to define a function `(a -> m b)`. Can someone provide some pedagogical example?

Original source