简体   繁体   中英

Scala Monoid Combinator for Options

Let's say that I have a Monoid trait as below:

trait Monoid[A] {
  def combine(a1: A, a2: A): A
  def identity: A
}

Now if I want to write an optionMonoid for this, I could write it like this:

val optionMonoid1 = new Monoid[Option[A]] {
  def combine(a1: Option[A], a2: Option[A2]) a1 orElse a2
  def identity = None
}

This given the fact that I do not know anything about the inner type in the Option. But what if I want to have the combine operator in such a way that I want to really combine the inner types in the Option?

One option:

trait Semigroup[A] {
  def combine(a1: A, a2: A): A
}

trait Monoid[A] extends Semigroup[A] {
  def identity: A
}

def optionMonoid2[A](implicit sgA: Semigroup[A]) = new Monoid[Option[A]] {
  def combine(a1: Option[A], a2: Option[A2]) = (a1, a2) match {
    case (Some(b1), Some(b2)) => Some(sgA.combine(b1, b2))
    case _ => a1.orElse(a2)
  }
  def identity = None
}

It's easy to verify monoid laws hold.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM