Is there a good way to deal with Option[Monoid[T]] mappend operations?

147 views Asked by At

If I have a Monoid[T] that has a zero and mappend, it seems to me logically that the result of

implicit myMonoid: Monoid[T] = ...

val x: T = thing() 
val y: Option[T] = none[T]
val z: Option[T] = Some(value)

val a: T = x.mappend(y)
val b: T = x.mappend(z)

val i: T = y.mappend(x)
val j: T = z.mappend(x)

for a and b should be identity and x.mappend(z.get) respectively. Similarly for i and j.

What I have right now looks like:

def combine(a: Option[T], b: Option[T]) = {
    a match {
        case None => b
        case Some(x) => x |+| b.getOrElse(myMonoid.zero)
    }
}

Is there a pre-existing construct to express this, or is this mathematically incorrect?

1

There are 1 answers

3
4lex1v On BEST ANSWER

If i'm not mistaken there should be a monoid for Option, so simple

def combine[T: Monoid](a: Option[T], b: Option[T]) = a |+| b

should work.