Last active
December 28, 2015 19:19
-
-
Save gakuzzzz/7549119 to your computer and use it in GitHub Desktop.
型クラスとimplicit conversion
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
import language.{implicitConversions, higherKinds} | |
trait Functor[A, Repr[_]] { | |
def fmap[B](f: A => B): Repr[B] | |
def fcompose[B, G[_]](implicit ev: A => Functor[B, G]): Functor[B, ({type λ[α] = Repr[G[α]]})#λ] = | |
new Functor[B, ({type λ[α] = Repr[G[α]]})#λ] { | |
def fmap[C](f: B => C): Repr[G[C]] = Functor.this.fmap(a => ev(a).fmap(f)) | |
} | |
} | |
object Functor { | |
def lift[A, B, F[_]](f: A => B)(implicit ev: F[A] => Functor[A, F]): F[A] => F[B] = _.fmap(f) | |
} | |
class ListFunctor[A](underlying: List[A]) extends Functor[A, List] { | |
def fmap[B](f: A => B): List[B] = underlying map f | |
} | |
object ListFunctor { | |
implicit def listToFunctor[A](l: List[A]): Functor[A, List] = new ListFunctor(l) | |
} | |
class OptionFunctor[A](underlying: Option[A]) extends Functor[A, Option] { | |
def fmap[B](f: A => B): Option[B] = underlying map f | |
} | |
object OptionFunctor { | |
implicit def optionToFunctor[A](o: Option[A]): Functor[A, Option] = new OptionFunctor(o) | |
} |
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
> console | |
[info] Starting scala interpreter... | |
[info] | |
import ListFunctor._ | |
import OptionFunctor._ | |
import language._ | |
Welcome to Scala version 2.10.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45). | |
Type in expressions to have them evaluated. | |
Type :help for more information. | |
scala> List(1, 2, 3).fmap(_ * 2) | |
res0: List[Int] = List(2, 4, 6) | |
scala> List(Some(1), None, Some(3)).fcompose.fmap(_ * 2) | |
res1: List[Option[Int]] = List(Some(2), None, Some(6)) | |
scala> Functor.lift[String, Int, List](_.toInt) | |
res2: List[String] => List[Int] = <function1> | |
scala> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment