Skip to content

Instantly share code, notes, and snippets.

@ukitaka
Created February 9, 2017 02:27
Show Gist options
  • Save ukitaka/dfa77a779123dfd3b3dc04e1c5395fd3 to your computer and use it in GitHub Desktop.
Save ukitaka/dfa77a779123dfd3b3dc04e1c5395fd3 to your computer and use it in GitHub Desktop.
Functorの合成
import scala.language.higherKinds
trait Functor[F[+_]] {
def map[A, B](a: F[A])(f: A => B): F[B]
}
implicit val optionalFunctor = new Functor[Option] {
def map[A, B](a: Option[A])(f: A => B): Option[B] = a.map(f)
}
implicit val seqFunctor = new Functor[Seq] {
def map[A, B](a: Seq[A])(f: A => B): Seq[B] = a.map(f)
}
def composeFunctor[F[+_]: Functor, G[+_]: Functor] = new Functor[({type f[+x] = F[G[x]]})#f] {
val F: Functor[F] = implicitly[Functor[F]]
val G: Functor[G] = implicitly[Functor[G]]
def map[A, B](a: F[G[A]])(f: (A) => B) = F.map(a)(G.map(_)(f))
}
implicit val cf = composeFunctor[Option, Seq]
val a: Option[Seq[Int]] = Some(Seq(1,2,3))
a.map(_.map(_ * 2)) // Some(Seq(2,4,6))
composeFunctor[Option, Seq].map(a)(_ * 2) // Some(Seq(2,4,6))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment