假设我有很多功能:
f :: a -> Maybe a
g :: a -> Maybe a
h :: a -> Maybe a
Run Code Online (Sandbox Code Playgroud)
我想用以下方式组合它们:如果f返回Nothing,则计算g.如果g返回Nothing,则计算h.如果其中任何一个计算Just a,请停止链.而整个构图(例如f)当然应该返回Maybe a.
这与Maybe monad的典型使用相反,如果返回Nothing,通常会停止计算.
用于链接这样的计算的Haskell成语是什么?
acf*_*zer 44
mplus正是你所寻找的,是MonadPlus类型类的一部分.这是它的定义:
instance MonadPlus Maybe where
mzero = Nothing
Nothing `mplus` ys = ys
xs `mplus` _ys = xs
Run Code Online (Sandbox Code Playgroud)
要在你的情况下使用它:
combined x = (f x) `mplus` (g x) `mplus` (h x)
Run Code Online (Sandbox Code Playgroud)