Last active
December 17, 2015 19:49
-
-
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
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
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