Created
March 13, 2012 01:55
-
-
Save mergeconflict/2026129 to your computer and use it in GitHub Desktop.
typeclass fu
This file contains 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
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) | |
} | |
} |
This file contains 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
// 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