Skip to content

Instantly share code, notes, and snippets.

@edofic
Created May 27, 2013 14:24
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 edofic/5657347 to your computer and use it in GitHub Desktop.
Save edofic/5657347 to your computer and use it in GitHub Desktop.
typeclasses and syntax in scala. monad example. this is approximately how scalaz works
trait Monad[M[_]] {
def apply[A](a: => A): M[A]
def flatMap[A,B](value: M[A], f: A => M[B]): M[B]
def map[A,B](value: M[A], f: A=>B): M[B] = flatMap(value, (v: A) => apply(f(v)))
}
object Monad {
def apply[A[_]](implicit f: Monad[A]) = f
}
object MonadSyntax {
implicit class MonadOps[A, M[_]: Monad](v: M[A]){
def map[B](f: A=>B) = Monad[M].map(v,f)
def flatMap[B](f: A=>M[B]) = Monad[M].flatMap(v,f)
}
}
//...
final case class Id[A](a: A)
//...
implicit object IdFM extends Monad[Id] {
def apply[A](a: => A) = Id(a)
def flatMap[A,B](value: Id[A], f: A => Id[B]): Id[B] = f(value.a)
}
//...
import MonadSyntax._
Id("foo").flatMap(s => Id(s.length))
for {
a <- Id(1)
b <- Id(2)
} yield a + b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment