Last active
March 3, 2016 23:27
-
-
Save mpilquist/06745de4d980b07529fc to your computer and use it in GitHub Desktop.
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
› scala | |
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_31). | |
Type in expressions to have them evaluated. | |
Type :help for more information. | |
scala> :paste | |
// Entering paste mode (ctrl-D to finish) | |
trait Monad[F[_]] { | |
def pure[A](a: A): F[A] | |
def bind[A, B](fa: F[A])(f: A => F[B]): F[B] | |
} | |
implicit class MonadOps[F[_], A](fa: F[A])(implicit F: Monad[F]) { | |
def fltn[B](implicit ev: A =:= F[B]): F[B] = F.bind(fa)(x => x) | |
def fltn2[B](implicit ev: A <:< F[B]): F[B] = F.bind(fa)(x => x) | |
def fltn3[B](implicit ev: A <:< F[B], ev2: F[B] <:< A): F[B] = F.bind(fa)(x => x) | |
} | |
implicit val mo = new Monad[Option] { | |
def pure[A](a: A) = Some(a) | |
def bind[A, B](fa: Option[A])(f: A => Option[B]) = fa.flatMap(f) | |
} | |
case class Invariant[A](a: A) | |
implicit val mi = new Monad[Invariant] { | |
def pure[A](a: A) = Invariant(a) | |
def bind[A, B](fa: Invariant[A])(f: A => Invariant[B]) = f(fa.a) | |
} | |
// Exiting paste mode, now interpreting. | |
warning: there were two feature warnings; re-run with -feature for details | |
defined trait Monad | |
defined class MonadOps | |
mo: Monad[Option]{def pure[A](a: A): Some[A]} = $anon$1@16267862 | |
defined class Invariant | |
mi: Monad[Invariant] = $anon$2@453da22c | |
scala> Option(Option(1)).fltn | |
<console>:17: error: Cannot prove that Option[Int] =:= Option[B]. | |
Option(Option(1)).fltn | |
^ | |
scala> Option(Option(1)).fltn2 | |
res1: Option[Int] = Some(1) | |
scala> Option(Option(1)).fltn3 | |
res2: Option[Int] = Some(1) | |
scala> Invariant(Invariant(1)).fltn | |
<console>:17: error: Cannot prove that Invariant[Int] =:= Invariant[B]. | |
Invariant(Invariant(1)).fltn | |
^ | |
scala> Invariant(Invariant(1)).fltn2 | |
res4: Invariant[Int] = Invariant(1) | |
scala> Invariant(Invariant(1)).fltn3 | |
res5: Invariant[Int] = Invariant(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment