Created
May 27, 2013 14:24
-
-
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
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
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