Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.