Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Maybe Monad in "reverse"

Tags:

haskell

monads

Let's say I have a number of functions:

f :: a -> Maybe a g :: a -> Maybe a h :: a -> Maybe a 

And I want to compose them in the following way: If f returns Nothing, compute g. If g returns Nothing, compute h. If any of them compute Just a, stop the chain. And the whole composition (h . g . f) should of course return Maybe a.

This is the reverse of the typical use of the Maybe monad, where typically you stop computing if Nothing is returned.

What's the Haskell idiom for chaining computations like this?

like image 603
Ara Vartanian Avatar asked Apr 09 '11 16:04

Ara Vartanian


2 Answers

mplus is exactly what you're looking for, part of the MonadPlus typeclass. Here's its definition:

instance MonadPlus Maybe where    mzero = Nothing     Nothing `mplus` ys  = ys    xs      `mplus` _ys = xs 

To use it in your case:

combined x = (f x) `mplus` (g x) `mplus` (h x)  
like image 111
acfoltzer Avatar answered Sep 21 '22 14:09

acfoltzer


mplus is probably better, but this should work as well:

import Data.List import Data.Maybe  import Control.Monad   join $ find isJust [f x, g y, h z] 
like image 22
Landei Avatar answered Sep 18 '22 14:09

Landei