[英]Using the Maybe Monad in “reverse”
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. 我想用以下方式组合它们:如果f返回Nothing,则计算g。 If g returns Nothing, compute h. 如果g返回Nothing,则计算h。 If any of them compute Just a, stop the chain. 如果其中任何一个计算Just a,请停止链。 And the whole composition (h . g . f) should of course return Maybe a. 而整个构图(例如f)当然应该返回Maybe a。
This is the reverse of the typical use of the Maybe monad, where typically you stop computing if Nothing is returned. 这与Maybe monad的典型使用相反,如果返回Nothing,通常会停止计算。
What's the Haskell idiom for chaining computations like this? 用于链接这样的计算的Haskell成语是什么?
mplus
is exactly what you're looking for, part of the MonadPlus
typeclass. mplus
正是您所寻找的,是MonadPlus
类型类的一部分。 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)
mplus
is probably better, but this should work as well: mplus
可能更好,但这应该也可以:
import Data.List
import Data.Maybe
import Control.Monad
join $ find isJust [f x, g y, h z]
I guess you mean: 我想你的意思是:
f,g,h:: a -> Maybe b
Using MonadPlus 使用MonadPlus
f x `mplus` g x `mplus` h x
You might want to use the StateT Monad: 您可能想要使用StateT Monad:
function = runReaderT $ ReaderT f `mplus` ReaderT g `mplus` ReaderT h
f,g,h are ReaderT a Maybe b (up to the ReaderT) f,g,h是ReaderT a Maybe b(由ReaderT决定)
or using msum: 或使用msum:
function = runReaderT $ msum $ map ReaderT [f,g,h]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.