Suppose I want to use implicitly
to simplify the appearance of my code and I'm writing a function that needs to use a Monoid
instance for one of the parameters, but the monoid is over a container type, such as A[B]
. For example:
trait Monoid[A] {
def mappend(a1: A, a2: A): A
def mzero: A
}
implicit def futureOfListMonoid[A] = new Monoid[Future[List[A]]] {
def mappend(a1: Future[List[A]], a2: Future[List[A]]) = {
for {
v1 <- a1
v2 <- a2
} yield (v1 ++ v2)
}
def mzero = Future.successful(Nil)
}
Suppose I want to write a generic function that operates over a generic monoid over a type container, such as in the following toy example:
// this compiles and works, but isn't good enough
// for my more complicated example, which need to
// specify that A is a container type
def myAppend[A: Monoid](a1: A, a2: A): A = {
implicitly[Monoid[A]].mappend(a1, a2)
}
// this is roughly what I want, but it doesn't compile
def myAppend[A[_]: Monoid, B](a1: A[B], a2: A[B]): A[B] = {
implicitly[Monoid[A[B]]].mappend(a1, a2)
}
Is there a way to make this work without using implicit parameters (I know this approach will work).
Editing to include a link to codereview.stackexchange of the more complicated example: https://codereview.stackexchange.com/questions/51571/custom-implementation-of-generic-future-sequence-in-scala