Let's say that I have a Monoid trait as below:
Now if I want to write an optionMonoid for this, I could write it like this:
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? 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 [hidden email]. For more options, visit https://groups.google.com/d/optout. |
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) } Cats implements it a bit differently: https://github.com/typelevel/cats/blob/v0.9.0/kernel/src/main/scala/cats/kernel/instances/option.scala#L61 They only require a Semigroup[A]. Op donderdag 20 april 2017 12:29:34 UTC+2 schreef Joe San:
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 [hidden email]. For more options, visit https://groups.google.com/d/optout. |
It makes sense with the cats implementation because a Semigroup already defines a combine operator! On Thu, Apr 20, 2017 at 1:57 PM, Jasper-M <[hidden email]> wrote:
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 [hidden email]. For more options, visit https://groups.google.com/d/optout. |
Yes if you define empty to be None, you only need the combine method so Semigroup is enough then.
-- 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 [hidden email]. For more options, visit https://groups.google.com/d/optout. |
Free forum by Nabble - Scala Resume Examples - Resume Templates | Edit this page |