Skip to content

Instantly share code, notes, and snippets.

@mushtaq
Forked from paulp/universal.scala
Last active February 12, 2016 01:14
Show Gist options
  • Save mushtaq/dadaa80ab5ef8a8f2fad to your computer and use it in GitHub Desktop.
Save mushtaq/dadaa80ab5ef8a8f2fad to your computer and use it in GitHub Desktop.
// [info] Running p.Run
// List(Fish(Bob, Esq.,12), Kitty(Thor, Esq.,java.awt.Color[r=255,g=200,b=0]))
package misc
import java.awt.Color
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)
}
}
trait Item[TC[x]] {
type Elm
def elm: Elm
def concept: TC[Elm]
}
object Item {
implicit def liftElm[TC[x], A: TC](x: A): Item[TC] = new Item[TC] {
type Elm = A
def elm = x
def concept = implicitly[TC[Elm]]
}
}
object Run {
def esquire(pet: Item[Pet]): pet.Elm = {
pet.concept.renamed(pet.elm, pet.concept.name(pet.elm) + ", Esq.")
}
def main(args: Array[String]): Unit = {
val bob = Fish("Bob", 12)
val thor = Kitty("Thor", Color.ORANGE)
val pets = List[Item[Pet]](bob, thor)
val renamed = pets map (x => esquire(x))
println(renamed)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment