Skip to content

Instantly share code, notes, and snippets.

@mergeconflict
Created March 13, 2012 01:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mergeconflict/2026129 to your computer and use it in GitHub Desktop.
Save mergeconflict/2026129 to your computer and use it in GitHub Desktop.
typeclass fu
object Hoho {
trait Foo[A] {
def phooey(): Unit
}
implicit def intFoo(i: Int): Foo[Int] = new Foo[Int] {
def phooey(): Unit = println("int " + i.toString)
}
implicit def stringFoo(s: String): Foo[String] = new Foo[String] {
def phooey(): Unit = println("string " + s)
}
def main(args: Array[String]): Unit = {
val l: List[Foo[_]] = List(1, "hoho")
l foreach (_.phooey)
}
}
// reifies the assertion that type A is an instance of typeclass F
final class instance[A, F[_]](value: A, typeclass: F[A]) {
def apply[B](f: (F[A], A) => B): B = f(typeclass, value)
}
// provides an implicit conversion from any A to the above "instance" wrapper
object instance {
implicit def anyToInstance[A, F[_]](a: A)(implicit fa: F[A]) = new instance(a, fa)
}
object Hoho {
trait Foo[A] {
def phooey(a: A): Unit
}
implicit object IntFoo extends Foo[Int] {
def phooey(a: Int): Unit = println("int " + a.toString)
}
implicit object StringFoo extends Foo[String] {
def phooey(a: String): Unit = println("string " + a.toString)
}
def main(args: Array[String]): Unit = {
val l: List[_ instance Foo] = List(1, "hoho")
l foreach (_(_ phooey _))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment