Reputation: 4781
I'm messing around with algebraic structures, and I find the Numeric
typeclass very handy for well, representing numeric values.
So I can write my monoid instance this way:
implicit def add[A: Numeric] = new Monoid[A] {
def mempty = implicitly[Numeric[A]].zero
def mappend(a0: A, a1: A) = implicitly[Numeric[A]].plus(a0, a1)
}
This looks like a dandy. But what can I do with sequences? I can't find a typeclass that does standard Scala collection sequences. I would like to write something like this:
def concat[A : SeqTC] = new Monoid[A] {
def mempty = implicitly[SeqTC[A]].empty
def mappend(a0: A, a1: A) = implicitly[SeqTC[A]].++(a0, a1)
}
Upvotes: 2
Views: 95
Reputation: 4781
According to @TrustNoOne's comment, this is what I achieved to do. And it works great.
def concat[A, S[A] <: Seq[A]](implicit bf: CanBuildFrom[S[A], A, S[A]]) = new Monoid[S[A]] {
def mempty = bf().result()
def mappend(a0: S[A], a1: S[A]) = bf.apply().++=(a0).++=(a1).result()
}
Upvotes: 1