Skip to content

Instantly share code, notes, and snippets.

@Centaur
Last active November 12, 2015 08:41
Show Gist options
  • Save Centaur/4462594aa94665905717 to your computer and use it in GitHub Desktop.
Save Centaur/4462594aa94665905717 to your computer and use it in GitHub Desktop.
Monad & Syntax
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