Skip to content

Instantly share code, notes, and snippets.

@lancelet
Created July 3, 2014 01:09
Show Gist options
  • Save lancelet/595a48ee9db984727e0b to your computer and use it in GitHub Desktop.
Save lancelet/595a48ee9db984727e0b to your computer and use it in GitHub Desktop.
Project typeclasses over collections?
import scala.collection.immutable._
object TypeclassProjection {
trait Show[T] {
def show(t: T): String
}
object Show {
def apply[T](showFn: T => String): Show[T] = new Show[T] { def show(t: T): String = showFn(t) }
}
def executeShow[T:Show](t: T): String = implicitly[Show[T]].show(t)
implicit val showInt: Show[Int] = Show(i => i.toString)
executeShow(42) // works OK
// everything below fails:
// attempt 1
implicit def showSeqA[T:Show](ss: Seq[T]): Show[Seq[T]] =
Show(_.map(implicitly[Show[T]].show).mkString(", "))
// attempt 2
implicit def showSeqB[A <% T, T:Show](ss: Seq[A]): Show[Seq[A]] =
Show(_.map(_.asInstanceOf[T]).map(implicitly[Show[T]].show).mkString(", "))
executeShow(Seq(19,42)) // can't perform typeclass lookup
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment