Reputation: 336
I'm trying to implement the following trait:
trait Monad[M[_]] {
def pure[A](a: A): M[A]
def flatMap[A, B](ma: M[A], f: A => M[B]): M[B]
}
for type Array:
def arrayMonad: Monad[Array] = new Monad[Array] {
def pure[A](a: A): Array[A] = Array(a)
def flatMap[A, B](a: Array[A], f: A => Array[B]): Array[B] = a flatMap f
}
The compiler complains that there are no ClassTags for A and B. If I add them (either with an implicit parameter or "[A: ClassTag]" style), I'm told that I'm missing implementations:
Missing implementations for 2 members. Stub implementations follow:
def flatMap[A, B](ma: Array[A], f: A => Array[B]): Array[B] = ???
def pure[A](a: A): Array[A] = ???
There may be something obvious I'm missing, but I'm not sure what it is.
Upvotes: 1
Views: 323
Reputation: 48400
Perhaps emulate Luis' contribution to cats Adding instances for ArraySeq #3273 and use untagged
factory to avoid having to provide implicit ClassTag
:
def arrayMonad: Monad[ArraySeq] = new Monad[ArraySeq] {
def pure[A](a: A): ArraySeq[A] = ArraySeq.untagged(a)
def flatMap[A, B](a: ArraySeq[A], f: A => ArraySeq[B]): ArraySeq[B] = a flatMap f
}
arrayMonad.pure(42)
// res0: scala.collection.immutable.ArraySeq[Int] = ArraySeq(42)
Upvotes: 1
Reputation: 170713
If you add them, then you change signature and are no longer overriding the original methods (add override
and you'll see "overrides nothing" error).
You simply can't implement Monad[Array]
for this definition of Monad
.
Upvotes: 3