How to use the maybe monoid and combine values with a custom operation, easily?

后端 未结 3 1029
轮回少年
轮回少年 2021-02-14 06:38

What I\'m trying to do is trivial to define by hand, basically

maybeCombine :: (a->a->a) -> Maybe a -> Maybe a -> Maybe a
maybeCombine _ Nothing N         


        
3条回答
  •  不知归路
    2021-02-14 07:03

    import Data.Monoid
    maybeCombine :: (a->a->a) -> Maybe a -> Maybe a -> Maybe a
    maybeCombine f mx my = let combine = mx >>= (\x -> my >>= (\y -> Just (f x y)))
                           in getFirst $ First combine `mappend` First mx `mappend` First` my
    

    in GHCi, this gives me

    *Main> maybeCombine (+) Nothing Nothing
    Nothing
    *Main> maybeCombine (+) (Just 3) Nothing
    Just 3
    *Main> maybeCombine (+) (Just 3) (Just 5)
    Just 8
    

    Also works with getLast if you put Last combine at the end of the mappend sequence

提交回复
热议问题