In Scastie, worksheet mode is enabled by default. which doesn’t allow package
statements. There’s a button in the top toolbar to disable it. You’ll also have to change the build settings to Scala 2.12 for the imports to work.
Regarding the implicit-not-found error: Your code does not define a Pairable[List]
. The other Pairable
instances for supertypes like the Pairable[Seq]
do not apply, because Pairable
isn’t covariant in F
. You also cannot make it covariant, because F
is used in argument types. I don’t know any simple solution that doesn’t require implementing it for every Seq
subclass you want to use. If you use cats (or another fp library), you can use the existing instances for Functor
and Foldable
:
implicitly def genPairable[F[_]:Foldable:Functor]: Pairable[F] = new Pairable[F] {
override def map[A, B](p: F[A], f: A => B): F[B] = Functor[F].map(p)(f)
override def foldLeft[A, B](p: F[A], z: B)(f: (B, A) => B): B = Foldable[F].foldLeft(p, z)(f)
}
or even just require Foldable
and Functor
in pairMapReduce
instead of Pairable
and define the paired
method with the Foldable
dependency:
def paired[A, B, F[_] : Foldable](tree: F[A], f: A => B): (List[(B, B)], Option[B]) = {
val none: Option[B] = None
val nil: List[(B, B)] = Nil
Foldable[F].foldLeft(tree, (nil, none)) {
case ((stack: List[(B, B)], Some(b: B)), a: A) => (((b, f(a)) :: stack), none)
case ((stack: List[(B, B)], None), a: A) => (stack, Some(f(a)))
} match {
case (stack, leftover) => (stack.reverse, leftover)
}
}
The latter solution doesn’t require an additional typeclass to be defined, but has the drawback, that cats doesn’t provide instances for mutable data types.
Another thing that will probably cause problems is your instance for Array
, because Arrays aren’t using type parameters on the JVM (although they look that way in Scala). This means, that you cannot create an Array of a generic type, which is why
def map[A, B](a:Array[A])(f: A => B): Array[B] = a.map(f)
will give a compiler error, because map will return an ArraySeq
. Creating an Array[B]
requires an implicit ClassTag[B]
, but that would no longer be compatible with your signature in the typeclass. So you probably can’t have the same implementation for Arrays and other collection types.