Created
March 4, 2019 14:55
-
-
Save erichonorez/b1546ce2ed7ce69c3fb9ef0150d4ba99 to your computer and use it in GitHub Desktop.
Functor test
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
trait Functor[M[_]] { | |
def map[A, B](ma: M[A], f: A => B): M[B] | |
def lift[A, B](f: A => B): M[A] => M[B] | |
} | |
object Functor { | |
def apply[F[_] : Functor]: Functor[F] = implicitly[Functor[F]] | |
implicit val optionIsFunctor = new Functor[Option] { | |
override def map[A, B](ma: Option[A], f: A => B): Option[B] = ma.map(f) | |
override def lift[A, B](f: A => B): Option[A] => Option[B] = ma => ma.map(f) | |
} | |
object ops { | |
def map[F[_] : Functor, A, B](fa: F[A], f: A => B): F[B] = Functor[F].map(fa, f) | |
def lift[F[_] : Functor, A, B](f: A => B): F[A] => F[B] = Functor[F].lift(f) | |
} | |
} | |
import Functor._ | |
import Functor.ops._ | |
val double: Int => Int = _ * 2 | |
println(Functor.optionIsFunctor.map(Some(1), double).get) | |
println(Functor[Option].map(Some(1), double).get) | |
val optional: Option[Int] = Some(1) | |
println(map(optional, double).get) | |
val f: Option[Int] => Option[Int] = lift(double) | |
println(f(optional)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment