Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/5606228/using-the-maybe-monad-in-reverse

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
293 views
Welcome To Ask or Share your Answers For Others

1 Answer

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) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...