63 lines
1.9 KiB
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 Either conforms to the following typeclasses:
|
|
* - Functor
|
|
* - Monad
|
|
*/
|
|
class EitherSpec extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers {
|
|
|
|
property("Either.map() preserves identity functions") {
|
|
forAll(arbitrary[Either[Exception, Int]]) { fa =>
|
|
fa.map(identity) mustBe identity(fa)
|
|
}
|
|
}
|
|
|
|
property("Either.map() preserves function composition") {
|
|
forAll(for {
|
|
fa <- arbitrary[Either[Exception, 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"Either.flatMap() preserves left identity") {
|
|
forAll(for {
|
|
a <- arbitrary[Int]
|
|
h <- arbitrary[Int => Either[Exception, String]]
|
|
} yield (a, h)) { case (a, h) =>
|
|
val leftIdentity = (x: Int) => Right(x).flatMap(h)
|
|
leftIdentity(a) mustBe h(a)
|
|
}
|
|
}
|
|
|
|
property(s"Either.flatMap() preserves right identity") {
|
|
forAll(for {
|
|
a <- arbitrary[Int]
|
|
h <- arbitrary[Int => Either[Exception, String]]
|
|
} yield (a, h)) { case (a, h) =>
|
|
val rightIdentity = h(_: Int).flatMap(Right(_))
|
|
rightIdentity(a) mustBe h(a)
|
|
}
|
|
}
|
|
|
|
property(s"Either.flatMap() is associative") {
|
|
forAll(for {
|
|
a <- arbitrary[Double]
|
|
f <- arbitrary[Double => Either[Exception, String]]
|
|
g <- arbitrary[String => Either[Exception, Int]]
|
|
h <- arbitrary[Int => Either[Exception, 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)
|
|
}
|
|
}
|
|
}
|