Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Monads in Scala
trait M[T] {
def flatMap[U](f: T => M[U]): M[U]
def unit[T](x: T): M[T]
}
val l = List(1)
l.map(x => x * 2)
l.flatMap(x => List(x * 2))
// left unit
def f(x:Int): List[Int] = List(x * 2)
l flatMap f
f(1)
// right unit
l.flatMap(List(_))
// associativity
def g(x:Int): List[Int] = List(x * 3)
l flatMap f flatMap g
l flatMap f flatMap(x => g(x))
l flatMap(x => f(x)) flatMap g
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment