Created
July 3, 2014 01:09
-
-
Save lancelet/595a48ee9db984727e0b to your computer and use it in GitHub Desktop.
Project typeclasses over collections?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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