Skip to content

Instantly share code, notes, and snippets.

@zmactep
Created May 17, 2016 09:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmactep/4995757687cd9edaeddfd97f284dffc8 to your computer and use it in GitHub Desktop.
Save zmactep/4995757687cd9edaeddfd97f284dffc8 to your computer and use it in GitHub Desktop.
Scala Functor
/*
class Functor f where
fmap :: (a -> b) -> f a -> f b
*/
trait Functor[F[_]] {
def fmap[A, B](f : F[A])(g : A => B) : F[B]
}
trait Applicative[F[_]] extends Functor[F] {
def pure[A] : F[A]
def ap[A, B](f : F[A => B])(g : F[A]) : F[B]
}
object ABC extends App {
/*
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap g (Just x) = Just (g x)
*/
implicit val optionIsAFunctor : Functor[Option] = new Functor[Option] {
override def fmap[A, B](f : Option[A])(g : (A) => B) : Option[B] =
f match {
case None => None
case Some(x) => Some(g(x))
}
}
/*
....
*/
implicit val listIsAFunctor : Functor[List] = new Functor[List] {
override def fmap[A, B](f : List[A])(g : (A) => B) : List[B] =
f match {
case Nil => Nil
case (x :: xs) => g(x) :: fmap(xs)(g)
}
}
val a : Option[Int] = Some(2)
val b = List(1,2,3)
def foo[F[_] : Functor, A, B](f : F[A])(g : A => B) : F[B] =
implicitly[Functor[F]].fmap(f)(g)
def bar[F[_], A, B](f : F[A])(g : A => B)(implicit functor : Functor[F]) : F[B] =
functor.fmap(f)(g)
println(foo(a)(i => i + 2))
println(bar(b)(i => i - 1))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment