Skip to content

Instantly share code, notes, and snippets.

@igstan
Last active January 25, 2017 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igstan/66e9bfd31d6ff03b233d to your computer and use it in GitHub Desktop.
Save igstan/66e9bfd31d6ff03b233d to your computer and use it in GitHub Desktop.
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)
}
}
@chrisdone
Copy link

There doesn't seem to be a point in using this if you have to pass the M around.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment