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