Skip to content

Instantly share code, notes, and snippets.

@adilakhter
Last active August 29, 2015 14:15
Show Gist options
  • Save adilakhter/82f5bb73cf1d7b5672a9 to your computer and use it in GitHub Desktop.
Save adilakhter/82f5bb73cf1d7b5672a9 to your computer and use it in GitHub Desktop.
TypeLambda #Scala
// Example HList with type member Hd
trait HList{
type Hd
}
class IntList extends HList {
type Hd = Int
}
// Example of TypeLambda
trait Functor[A, +M[_]]{
def map[B](f: A => B): M[B]
}
case class ListFunctor[A](seq: Seq[A]) extends Functor[A, Seq]{
override def map[B](f: (A) => B): Seq[B] = seq.map(f)
}
case class MapFunctor[K,V](mapKV: Map[K,V]) extends Functor[V, ({type L[a] = Map[K,a]})#L]{
override def map[V2](f: V => V2): Map[K, V2] = mapKV map{
case (k,v) => (k, f(v))
}
}
case class ReadableMapFunctor[K,V](mapKV: Map[K,V]){
def mapFunctor[V2] = {
type `Map[K]`[V2] = Map[K, V2]
new Functor[V, `Map[K]`] {
override def map[V2](f: (V) => V2): `Map[K]`[V2] = mapKV map{
case (k,v) => (k, f(v))
}
}
}
object TypeLambdaDemo extends App{
//type projection with #
implicitly[Int =:= IntList#Hd]
val x: IntList#Hd = 10
//list functor
val lst = ListFunctor(List(1,2,3)).map(_ * 10)
println(lst)
//map functor
val mapKV = MapFunctor(Map(1->1, 2->2, 3->3)).map(_ * 10)
println(mapKV)
val mapKV2 = ReadableMapFunctor(Map(1->1, 2->2, 3->3)).mapFunctor.map(_*10)
println(mapKV2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment