Created
September 29, 2018 18:01
-
-
Save justinhj/d49bf72686924348a96d09b6667b314c to your computer and use it in GitHub Desktop.
Example of using a type lambda for implementing Functor over Maps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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