Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ilijaljubicic/78402207284f96767c61401d91143a1f to your computer and use it in GitHub Desktop.
Save ilijaljubicic/78402207284f96767c61401d91143a1f to your computer and use it in GitHub Desktop.
Monad Laws Example on scala List Monad
/*
Monads laws examples with List monads
Summary from article: https://devth.com/2015/monad-laws-in-scala
*/
val f: (Int => List[Int]) = x => List(x - 1, x, x + 1)
val g: (Int => List[Int]) = x => List(x, -x)
val unitX = List(2) //list monad
/*
left identity law:
unit(x).flatMap(f) == f(x)
*/
val lhs=unitX.flatMap(f)
val rhs=f(1)
println(lhs)
println (rhs)
println(lhs==rhs)
/*
right-identity law:
unit(x).flatMap(unit) ==unit(x)
*/
val lhs1 = unitX.flatMap(x=>List(x))
val rhs1=unitX
println(lhs1)
println(rhs1)
println(lhs1==rhs1)
/*
associativity law:
unit(x).flatMap(f).flatMap(g) == unit(x).flatMap(x ⇒ f(x).flatMap(g))
*/
val lhs2=unitX.flatMap(f).flatMap(g)
val rhs2=unitX.flatMap(x=>f(x).flatMap(g))
println(lhs2)
println(rhs2)
println(lhs2==rhs2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment