Option Monoid with deep combine

62 views
Skip to first unread message

Joe San

unread,
Apr 20, 2017, 6:29:34 AM4/20/17
to scala-user

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?

Jasper-M

unread,
Apr 20, 2017, 7:57:38 AM4/20/17
to scala-user
That probably means a Monoid[A] needs to exist. You can encode that dependency with an implicit parameter or context bound. Assuming you encode typeclass instances with implicits.

For instance:

implicit def optionMonoid[A](implicit monoidA: Monoid[A]): Monoid[Option[A]] = new Monoid[Option[A]] {
  def combine(a1: Option[A], a2: Option[A]) = a1.flatMap(aa1 => a2.map(aa2 => monoidA.combine(aa1, aa2)))
  def identity = Option(monoidA.identity)
They only require a Semigroup[A].

Op donderdag 20 april 2017 12:29:34 UTC+2 schreef Joe San:

Joe San

unread,
Apr 20, 2017, 8:01:26 AM4/20/17
to scala-user
It makes sense with the cats implementation because a Semigroup already defines a combine operator!

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jasper-M

unread,
Apr 20, 2017, 8:10:01 AM4/20/17
to scala-user
Yes if you define empty to be None, you only need the combine method so Semigroup is enough then.
Reply all
Reply to author
Forward
0 new messages