Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active February 7, 2019 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frgomes/18c0b6cfe0c270d8a41f741685c54af5 to your computer and use it in GitHub Desktop.
Save frgomes/18c0b6cfe0c270d8a41f741685c54af5 to your computer and use it in GitHub Desktop.
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))
}
@frgomes
Copy link
Author

frgomes commented Feb 7, 2019

Demonstration of polymorphic typelevel programming.
More tricks here: https://vimeo.com/165837504

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment