Created
December 9, 2014 15:18
-
-
Save fsarradin/5806bc6324f44161304e to your computer and use it in GitHub Desktop.
Reader functor in Scala (the typeclass way)
This file contains hidden or 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
object FunctorModule { | |
trait Functor[F[_]] { | |
def map[A, B](f: A => B): F[A] => F[B] | |
} | |
implicit class ReaderFunctor[E](r: E => _) extends Functor[({ type l[a] = E => a })#l] { | |
override def map[A, B](f: A => B): (E => A) => (E => B) = { r => r andThen f } | |
} | |
implicit def functorOps[F[_]: Functor, A](fa: F[A]) = new { | |
val functor = implicitly[Functor[F]] | |
final def map[B](f: A => B): F[B] = functor.map(f)(fa) | |
} | |
def main(args: Array[String]) { | |
val f: (Int) => Int = (_: Int) * 5 | |
val g: (Int) => Int = (_: Int) + 3 | |
// what a type!? | |
val h: ((Int) => Int) => (Int) => Int = f map g | |
// compilation error here because 8 of type Int doesn't match (Int) => Int | |
println(h(8)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The whole solution 😄