Created
September 12, 2013 19:25
-
-
Save aaronlevin/6542596 to your computer and use it in GitHub Desktop.
A question came up during a talk I gave about how to provide a witness for the below `Functor` implementation. This is one (terrible) way to do it and should highlight how implicits can be used to provide the witness. There are definitely better ways to do this.
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
sealed trait Option2[+A] | |
case object None2 extends Option2[Nothing] | |
case class Some2[A](value: A) extends Option2[A] | |
trait Functor[F[_]] { | |
def map[A,B](f: A => B): F[A] => F[B] | |
} | |
implicit object optionFunctor extends Functor[Option2] { | |
def map[A,B](f: A => B): Option2[A] => Option2[B] = (oa: Option2[A]) => oa match { | |
case None2 => None2 | |
case Some2(a) => Some2(f(a)) | |
} | |
} | |
implicit def getFunctor[A[_] : Functor](a: A[_]): Functor[A] = { | |
implicitly[Functor[A]] | |
} | |
object MainProgram { | |
def doThing(i: Int): String = i.toString | |
def main(args: Array[String]) { | |
val tmp: Option2[Int] = Some2(1) | |
val opFunc: Option2[Int] => Option2[String] = tmp.map(doThing) | |
println("*** the result: %s".format(opFunc(tmp))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment