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 either and either_ #382

Merged
merged 1 commit into from
May 18, 2020
Merged
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
27 changes: 26 additions & 1 deletion hedgehog/src/Hedgehog/Internal/Gen.hs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ module Hedgehog.Internal.Gen (

-- ** Collections
, maybe
, either
, either_
, list
, seq
, nonEmpty
Expand Down Expand Up @@ -217,7 +219,7 @@ import qualified Data.Text.Encoding as Text
import Data.Word (Word8, Word16, Word32, Word64)

import Hedgehog.Internal.Distributive (MonadTransDistributive(..))
import Hedgehog.Internal.Prelude hiding (maybe, seq)
import Hedgehog.Internal.Prelude hiding (either, maybe, seq)
import Hedgehog.Internal.Seed (Seed)
import qualified Hedgehog.Internal.Seed as Seed
import qualified Hedgehog.Internal.Shrink as Shrink
Expand Down Expand Up @@ -1354,6 +1356,29 @@ maybe gen =
, (1 + fromIntegral n, Just <$> gen)
]

-- | Generates either an 'a' or a 'b'.
--
-- As the size grows, this generator generates @Right@s more often than @Left@s.
--
either :: MonadGen m => m a -> m b -> m (Either a b)
either genA genB =
sized $ \n ->
frequency [
(2, Left <$> genA)
, (1 + fromIntegral n, Right <$> genB)
]

-- | Generates either an 'a' or a 'b', without bias.
--
-- This generator generates as many @Right@s as it does @Left@s.
--
either_ :: MonadGen m => m a -> m b -> m (Either a b)
either_ genA genB =
choice [
Left <$> genA
, Right <$> genB
]

-- | Generates a list using a 'Range' to determine the length.
--
list :: MonadGen m => Range Int -> m a -> m [a]
Expand Down