Last active
February 7, 2019 23:59
-
-
Save frgomes/18c0b6cfe0c270d8a41f741685c54af5 to your computer and use it in GitHub Desktop.
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 TypelevelPolymorphic extends App { | |
object square extends Poly { | |
import scala.language.reflectiveCalls | |
implicit val is = at[Int] { i => i * i } | |
implicit val fs = at[Float] { f => f * f } | |
implicit val ds = at[Double] { d => d * d } | |
} | |
trait Poly { | |
def apply[A,B](a: A)(implicit f: Case[A,B]): B = f(a) | |
final def at[A] = new { | |
def apply[B](f: A => B): Case[A,B] = | |
new Case[A,B] { | |
def apply(a: A): B = f(a) | |
} | |
} | |
} | |
sealed trait Case[A,B] { | |
def apply(a: A): B | |
} | |
import square._ | |
println(square(4)) | |
println(square(1.61f)) | |
println(square(3.14d)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demonstration of polymorphic typelevel programming.
More tricks here: https://vimeo.com/165837504