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

后端 未结 3 1038
轮回少年
轮回少年 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:01

    You can always use

    f <$> m <*> n <|> m <|> n
    

    But this, sadly, doesn't have a canonical implementation anywhere.

    You can use reflection to get that (a -> a -> a) "baked in" as the Semigroup for use with Option, which is provided by semigroups as an improved version of Maybe that has the 'right' instance for Monoid in terms of Semigroup. This is rather too heavy handed for this problem though. =)

    Perhaps this should just be added as a combinator to Data.Maybe.

提交回复
热议问题