Skip to content

Instantly share code, notes, and snippets.

@khajavi
Last active July 1, 2016 12:17
Show Gist options
  • Select an option

  • Save khajavi/e398f297f3dfd9a0b40007bddd5365ff to your computer and use it in GitHub Desktop.

Select an option

Save khajavi/e398f297f3dfd9a0b40007bddd5365ff to your computer and use it in GitHub Desktop.
object monadLaws extends App {
// To qualify as a monald, a type has to satisfy three laws:
// Associativity
// (m flatMap f) flatMap g = m flatMap (x => f(x) flatMap g)
val f = (a: Int) => List(a)
val g = (a: Int) => List(a - 1, a + 1)
val m1 = 1 to 2
val r1 = m1 flatMap f flatMap g
val r2 = m1 flatMap (x => f(x) flatMap g)
assert(r1 == r2)
// Left identity:
// unit(x) flatMap f == f(x)
val unit = (a: Int) => List(a)
assert(unit(2).flatMap(f) == f(2))
// Right identity:
// m flatMap unit = m
assert(List(2).flatMap(unit) == List(2))
assert(List(2).flatMap((a: Int) => List(a)) == List(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment