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

后端 未结 3 1028
轮回少年
轮回少年 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 06:39

    You're right on the money when you notice that the f is like a Monoid operation on the underlying a type. More specifically what's going on here is you're lifting a Semigroup into a Monoid by adjoining a zero (mempty), Nothing.

    This is exactly what you see in the Haddocks for the Maybe Monoid actually.

    Lift a semigroup into Maybe forming a Monoid according to http://en.wikipedia.org/wiki/Monoid: "Any semigroup S may be turned into a monoid simply by adjoining an element e not in S and defining ee = e and es = s = s*e for all s ∈ S." Since there is no "Semigroup" typeclass providing just mappend, we use Monoid instead.

    Or, if you like the semigroups package, then there's Option which has exactly this behavior, suitably generalized to use an underlying Semigroup instead.


    So that suggests the clearest way is to define either a Monoid or Semigroup instance on the underlying type a. It's a clean way to associate some combiner f with that type.

    What if you don't control that type, don't want orphan instances, and think a newtype wrapper is ugly? Normally you'd be out of luck, but this is one place where using the total black magic, effectively GHC-only reflection package comes in handy. Thorough explanations exist in the paper itself but Ausin Seipp's FP Complete Tutorial includes some example code to allow you to "inject" arbitrary semigroup products into types without (as much) type definition noise... at the cost of a lot scarier signatures. 

    That's probably significantly more overhead than its worth, however.

提交回复
热议问题