Skip to content

Instantly share code, notes, and snippets.

@alexandrelanglais
Created August 25, 2017 08:01
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 alexandrelanglais/6a44c07881d842b03949d31cffd29837 to your computer and use it in GitHub Desktop.
Save alexandrelanglais/6a44c07881d842b03949d31cffd29837 to your computer and use it in GitHub Desktop.
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