我想要做的事情通过手工定义是微不足道的,基本上
maybeCombine :: (a->a->a) -> Maybe a -> Maybe a -> Maybe a
maybeCombine _ Nothing Nothing = Nothing
maybeCombine _ (Just a) Nothing = Just a
maybeCombine _ Nothing (Just a) = Just a
maybeCombine f (Just a) (Just a') = Just $ f a a'
在需要时定义此局部并不是什么大问题,但仍然很繁琐,而且这似乎是一个基本的通用问题,应该有一个标准的实现,但我似乎找不到。
也许我只是忽略了一些东西。我想要的与maybe monad的行为完全无关,因此我认为在Monad / Arrow抽屉中找不到任何东西; 但它确实类似于Monoid
实例
预处理Data.Monoid> Just "a" <> Nothing
Just "a"
预处理Data.Monoid> Just "a" <> Just "b"
Just "ab"
...
…但是它要求a
本身是一个monoid,即它基本上具有内置的a->a->a
。 MonadPlus
实例的行为也很符合我所需的,但它只是扔掉其中一个值,而不是允许我提供一个组合函数
Prelude Data.Monoid Control.Monad> Just 4 `mplus` Nothing Just 4 Prelude Data.Monoid Control.Monad> Nothing `mplus` Just 4 Just 4 Prelude Data.Monoid Control.Monad> Just 4 `mplus` Just 5 Just 4什么是规范解决方案? 本地模式匹配?使用例如
Data.Maybe
的组合器?定义自定义Monoid来进行组合?
Alternative
!这个很不错,但我觉得我更喜欢Semigroup
的优雅。 - leftaroundabout