Skip to content

Instantly share code, notes, and snippets.

@stew
Last active December 17, 2015 19:49
Show Gist options
  • Save stew/5662978 to your computer and use it in GitHub Desktop.
Save stew/5662978 to your computer and use it in GitHub Desktop.
You can create a generic monad transformer as long as the "inner" monad has a Traverse instance
import scalaz._
import Scalaz._
object MonadT {
implicit def monadTransformerFromTraverse[M[_]: Monad, N[_]: Monad: Traverse]: Monad[({type MN[A]=M[N[A]]})#MN] = new Monad[({type MN[A]=M[N[A]]})#MN] {
def point[A](a: => A): M[N[A]] = a.point[N].point[M]
def bind[A,B](fa: M[N[A]])(f: A=>M[N[B]]) : M[N[B]] = {
val M = implicitly[Monad[M]]
val NT = implicitly[Traverse[N]]
val N = implicitly[Monad[N]]
M.map(M.join(M.map(M.map(fa)(N.map(_)(f)))(NT.sequence(_))))(N.join)
// |- => M[N[M[N[B]]]] -|
// |- => M[M[N[N[B]]]] -|
// |- => M[N[N[B]]] -|
// |- => M[N[B]] -|
}
}
def main(argv: Array[String]) {
val x: Option[Option[Int]] = Some(Some(1))
val f: Int => Option[Option[Int]] = { x: Int => Some(Some(x+1)) }
val MT = monadTransformerFromTraverse[Option, Option]
println(MT.bind(x)(f)) // Some(Some(2))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment