Skip to content

Instantly share code, notes, and snippets.

@paulp
Created May 6, 2015 16:21
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save paulp/970d6ca190da7949754c to your computer and use it in GitHub Desktop.
Save paulp/970d6ca190da7949754c to your computer and use it in GitHub Desktop.
existentials are inverted universals
// [info] Running p.Run
// List(Fish(Bob, Esq.,12), Kitty(Thor, Esq.,java.awt.Color[r=255,g=200,b=0]))
import java.awt.Color
package p {
trait Pet[A] {
def name(a: A): String
def renamed(a: A, newName: String): A
}
case class Fish(name: String, age: Int)
case class Kitty(name: String, color: Color)
object Fish {
implicit object FishPet extends Pet[Fish] {
def name(a: Fish) = a.name
def renamed(a: Fish, newName: String) = a.copy(name = newName)
}
}
object Kitty {
implicit object KittyPet extends Pet[Kitty] {
def name(a: Kitty) = a.name
def renamed(a: Kitty, newName: String) = a.copy(name = newName)
}
}
object Run {
def main(args: Array[String]): Unit = {
val bob = Fish("Bob", 12)
val thor = Kitty("Thor", Color.ORANGE)
val pets = List[Parapet[_]](bob, thor)
val renamed = pets map (x => esquire(x))
println(renamed)
}
}
}
package object p {
type Parapet[A] = ((A, Pet[A]))
implicit def liftParapet[A: Pet](x: A): Parapet[A] = ((x, implicitly))
def esquire[A](p: Parapet[A]): A = p._2.renamed(p._1, p._2.name(p._1) + ", Esq.")
}
@mushtaq
Copy link

mushtaq commented May 7, 2015

@paulp, I tried to make it a bit complicated https://gist.github.com/mushtaq/dadaa80ab5ef8a8f2fad

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