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.subset #451

Merged
merged 2 commits into from
Feb 22, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions hedgehog/src/Hedgehog/Gen.hs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ module Hedgehog.Gen (

-- ** Combinations & Permutations
, subsequence
, subset
, shuffle

-- ** Abstract State Machine
Expand Down
15 changes: 15 additions & 0 deletions hedgehog/src/Hedgehog/Internal/Gen.hs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ module Hedgehog.Internal.Gen (

-- ** Combinations & Permutations
, subsequence
, subset
, shuffle
, shuffleSeq

Expand Down Expand Up @@ -215,6 +216,7 @@ import qualified Data.Semigroup as Semigroup
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
Expand Down Expand Up @@ -1665,6 +1667,19 @@ subsequence :: MonadGen m => [a] -> m [a]
subsequence xs =
shrink Shrink.list $ filterM (const bool_) xs

-- | Generates a random subset of a set.
--
-- /This shrinks towards the empty set./
--
subset :: MonadGen m => Set a -> m (Set a)
-- Set.fromDistinctAscList has an unchecked precondition that the list
-- must be strictly ascending. This precondition is satisfied because
-- Set.toAscList produces a strictly ascending list, and the 'subsequence'
-- generator only removes elements from the list; it never adds or
-- rearranges elements, so the strictly ascending property is undisturbed.
subset =
fmap Set.fromDistinctAscList . subsequence . Set.toAscList

-- | Generates a random permutation of a list.
--
-- /This shrinks towards the order of the list being identical to the input/
Expand Down