Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Gen.fix to make recursive generators cleaner #616

Merged
merged 1 commit into from
Mar 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions jvm/src/test/scala/org/scalacheck/GenSpecification.scala
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,28 @@ object GenSpecification extends Properties("Gen") with GenSpecificationVersionSp
}
}

property("fix is like lzy") = forAll { (seeds: List[Seed]) =>
lazy val lzyGen: Gen[List[Int]] = {
Gen.choose(0, 10).flatMap { idx =>
if (idx < 5) lzyGen.map(idx :: _)
else Gen.const(idx :: Nil)
}
}

val fixGen =
Gen.fix[List[Int]] { recurse =>
Gen.choose(0, 10).flatMap { idx =>
if (idx < 5) recurse.map(idx :: _)
else Gen.const(idx :: Nil)
}
}

val params = Gen.Parameters.default
seeds.forall { seed =>
lzyGen.pureApply(params, seed) == fixGen.pureApply(params, seed)
}
}

property("uuid version 4") = forAll(uuid) { _.version == 4 }

property("uuid unique") = forAll(uuid, uuid) {
Expand Down
17 changes: 17 additions & 0 deletions src/main/scala/org/scalacheck/Gen.scala
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,23 @@ object Gen extends GenArities with GenVersionSpecific {
/** A generator that never generates a value */
def fail[T]: Gen[T] = gen((p, seed) => failed[T](seed))


/**
* A fixed point generator. This is useful for making recusive structures
* e.g.
*
* Gen.fix[List[Int]] { recurse =>
* Gen.choose(0, 10).flatMap { idx =>
* if (idx < 5) recurse.map(idx :: _)
* else Gen.const(idx :: Nil)
* }
* }
*/
def fix[A](fn: Gen[A] => Gen[A]): Gen[A] = {
lazy val result: Gen[A] = lzy(fn(result))
result
}

/** A result that never contains a value */
private[scalacheck] def failed[T](seed0: Seed): R[T] =
new R[T] {
Expand Down