Last active
November 12, 2015 08:41
-
-
Save Centaur/4462594aa94665905717 to your computer and use it in GitHub Desktop.
Monad & Syntax
This file contains hidden or 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 HKind { | |
trait Monad[M[_]] { | |
def flatMap[T, U](m: M[T], f: T => M[U]): M[U] | |
def map[T, U](m: M[T], f: T => U): M[U] | |
} | |
implicit class MonadSyntax[X, M[_] : Monad](sx: M[X]) { | |
def flatMap[U](f: X => M[U]): M[U] = implicitly[Monad[M]].flatMap(sx, f) | |
def map[U](f: X => U): M[U] = implicitly[Monad[M]].map(sx, f) | |
} | |
def map2Monad[A, B, C, M[_] : Monad](sa: M[A], sb: => M[B])(f: (A, B) => C): M[C] = { | |
val monad = implicitly[Monad[M]] | |
// without syntax | |
monad.flatMap(sa, (a: A) => monad.map(sb, (b: B) => f(a, b))) | |
// with syntax | |
for (a <- sa; b <- sb) yield f(a, b) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment