From 9cb731937451bce5367e9f74d9e61ee6beefc6ca Mon Sep 17 00:00:00 2001 From: Cody Allen Date: Sat, 12 May 2018 09:30:50 -0700 Subject: [PATCH] Add Gen.either And make the Arbitrary instance for Either delegate to it. --- src/main/scala/org/scalacheck/Arbitrary.scala | 2 +- src/main/scala/org/scalacheck/Gen.scala | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/scala/org/scalacheck/Arbitrary.scala b/src/main/scala/org/scalacheck/Arbitrary.scala index f543e95de..bd6e0570f 100644 --- a/src/main/scala/org/scalacheck/Arbitrary.scala +++ b/src/main/scala/org/scalacheck/Arbitrary.scala @@ -346,7 +346,7 @@ private[scalacheck] sealed trait ArbitraryLowPriority { /** Arbitrary instance of the Either type */ implicit def arbEither[T, U](implicit at: Arbitrary[T], au: Arbitrary[U]): Arbitrary[Either[T, U]] = - Arbitrary(oneOf(arbitrary[T].map(Left(_)), arbitrary[U].map(Right(_)))) + Arbitrary(Gen.either(at.arbitrary, au.arbitrary)) /** Arbitrary instance of the Future type */ implicit def arbFuture[T](implicit a: Arbitrary[T]): Arbitrary[Future[T]] = diff --git a/src/main/scala/org/scalacheck/Gen.scala b/src/main/scala/org/scalacheck/Gen.scala index 638995d71..952ac8385 100644 --- a/src/main/scala/org/scalacheck/Gen.scala +++ b/src/main/scala/org/scalacheck/Gen.scala @@ -546,6 +546,10 @@ object Gen extends GenArities{ def some[T](g: Gen[T]): Gen[Option[T]] = g.map(Some.apply) + /** Generates a `Left` of `T` or a `Right` of `U` with equal probability. */ + def either[T, U](gt: Gen[T], gu: Gen[U]): Gen[Either[T, U]] = + oneOf(gt.map(Left(_)), gu.map(Right(_))) + /** Chooses one of the given generators with a weighted random distribution */ def frequency[T](gs: (Int, Gen[T])*): Gen[T] = { val filtered = gs.iterator.filter(_._1 > 0).toVector