Last active
January 25, 2017 22:11
-
-
Save igstan/66e9bfd31d6ff03b233d 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
object monads { | |
// Needed for the `M[_]` notation. | |
import scala.language.higherKinds | |
// The typeclass represented using a trait. | |
trait Monad[M[_]] { | |
def unit[A](a: A): M[A] | |
def bind[A,B](a: M[A])(f: A => M[B]): M[B] | |
} | |
object Monad { | |
// Monad instance for Option. | |
implicit val optionMonad: Monad[Option] = new Monad[Option] { | |
def unit[A](a: A): Option[A] = Some(a) | |
def bind[A,B](m: Option[A])(f: A => Option[B]): Option[B] = m.flatMap(f) | |
} | |
} | |
// Sample usage. | |
def main(args: Array[String]): Unit = { | |
val M = implicitly[Monad[Option]] | |
M.unit(1) // Some(1) | |
M.bind(M.unit(1)) { a => M.unit(a * 2) } // Some(2) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There doesn't seem to be a point in using this if you have to pass the
M
around.