scala - How to create a generic Monoid from an ADT -
given have existing adt, possible create generic monoid.
from now, have many monoid classes in adt, it's not dry.
here code :
import scalaz._ import scalaz._ object datarework extends app { sealed trait multiitemvalue { type mv def value: seq[mv] } case class stringvalue(value: seq[string]) extends multiitemvalue{type mv = string} case class booleanvalue(value: seq[boolean]) extends multiitemvalue{type mv = boolean} implicit object booleanvaluemonoid extends monoid[booleanvalue] { override def zero: booleanvalue = booleanvalue(nil) override def append(f1: booleanvalue, f2: => booleanvalue): booleanvalue = booleanvalue(f1.value ++ f2.value) } implicit object stringvaluemonoid extends monoid[stringvalue] { override def zero: stringvalue = stringvalue(nil) override def append(f1: stringvalue, f2: => stringvalue): stringvalue = stringvalue(f1.value ++ f2.value) }
i like, found code ugly due repetition :
implicit object genericmonoid extends monoid[multiitemvalue] { override def zero: multiitemvalue = ??? override def append(f1: multiitemvalue, f2: => multiitemvalue): multiitemvalue = (f1, f2) match { case (sv1: stringvalue, sv2: stringvalue) => stringvalue(sv1.value ++ sv2.value) case (bv1: booleanvalue, bv2: booleanvalue) => booleanvalue(bv1.value ++ bv2.value) } }
Comments
Post a Comment