Skip to content

Instantly share code, notes, and snippets.

@justinhj
Created September 29, 2018 18:01
Show Gist options
  • Save justinhj/d49bf72686924348a96d09b6667b314c to your computer and use it in GitHub Desktop.
Save justinhj/d49bf72686924348a96d09b6667b314c to your computer and use it in GitHub Desktop.
Example of using a type lambda for implementing Functor over Maps
// Functor
trait JFunctor[F[_]] {
def map[A,B](fa: F[A])(f: A => B) : F[B]
}
trait JMapFunctor[K] extends JFunctor[({type LT[V] = Map[K, V]})#LT] {
def map[A, B](fa: Map[K,A])(f: A => B): Map[K,B] = {
fa.foldLeft(Map.empty[K,B]) {
case (acc, (k,a)) =>
acc updated (k, f(a))
}
}
}
object JLongMap extends JMapFunctor[Long]
LongMap.map(Map(1L -> "Hello", 2L -> "Goodbye")){_.length}
// Map[Long, Int] = Map(1L -> 5, 2L -> 7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment