embracing-nondeterminism-code/src/test/scala/green/thisfieldwas/embracingnondeterminism/stdlib/OptionSpec.scala

63 lines
1.9 KiB
Scala

package green.thisfieldwas.embracingnondeterminism.stdlib
import org.scalacheck.Arbitrary.arbitrary
import org.scalatest.matchers.must.Matchers
import org.scalatest.propspec.AnyPropSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
/** Proves that Scala's Option conforms to the following typeclasses:
* - Functor
* - Monad
*/
class OptionSpec extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers {
property("Option.map() preserves identity functions") {
forAll(arbitrary[Option[Int]]) { fa =>
fa.map(identity) mustBe identity(fa)
}
}
property("Option.map() preserves function composition") {
forAll(for {
fa <- arbitrary[Option[Double]]
f <- arbitrary[Double => String]
g <- arbitrary[String => Int]
} yield (fa, f, g)) { case (fa, f, g) =>
fa.map(g compose f) mustBe fa.map(f).map(g)
}
}
property(s"Option.flatMap() preserves left identity") {
forAll(for {
a <- arbitrary[Int]
h <- arbitrary[Int => Option[String]]
} yield (a, h)) { case (a, h) =>
val leftIdentity = (x: Int) => Option(x).flatMap(h)
leftIdentity(a) mustBe h(a)
}
}
property(s"Option.flatMap() preserves right identity") {
forAll(for {
a <- arbitrary[Int]
h <- arbitrary[Int => Option[String]]
} yield (a, h)) { case (a, h) =>
val rightIdentity = h(_: Int).flatMap(Option(_))
rightIdentity(a) mustBe h(a)
}
}
property(s"Option.flatMap() is associative") {
forAll(for {
a <- arbitrary[Double]
f <- arbitrary[Double => Option[String]]
g <- arbitrary[String => Option[Int]]
h <- arbitrary[Int => Option[Boolean]]
} yield (a, f, g, h)) { case (a, f, g, h) =>
val assocLeft = f(_: Double).flatMap(g).flatMap(h)
val assocRight = f(_: Double).flatMap(g(_).flatMap(h))
assocLeft(a) mustBe assocRight(a)
}
}
}