Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maybe monad usage example

Tags:

haskell

monads

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?

like image 956
Aslan986 Avatar asked Nov 29 '22 02:11

Aslan986


1 Answers

A fairly common example with the Maybe monad is division. In some ways, the Maybe monad represents a computation that either gives a result (Just) or fails (Nothing), and division is precisely this: it works unless you are dividing by 0, in which case it is a failure.

Code is always useful:

divide :: (Fractional a) => a -> a -> Maybe a
divide a 0 = Nothing
divide a b = Just $ a / b

Some examples of using this function:

> divide 1 2
Just 0.5
> divide 20 3
Just 6.666666666666667
> divide 1 0 -- Oops
Nothing

Because Maybe is a monad, we can have computations that use this divide function and automatically propagate any errors. E.g. the following computes 1/x + 1 safely

recipPlusOne :: (Fractional a) => a -> Maybe a
recipPlusOne x = divide 1 x >>= return . (+1)

-- equivalently,
recipPlusOne' x = fmap (+1) $ divide 1 x

(Notice how return . (+1) is a function a -> m b, since it takes a number, adds one ((+1)), and then wraps it in the Maybe monad (return).)

And the errors propagate through,

> recipPlusOne 1
Just 2.0
> recipPlusOne 0.1
Just 11.0
> recipPlusOne 0 -- Oops, divide by 0
Nothing
like image 77
huon Avatar answered Dec 05 '22 06:12

huon