Skip to content

Commit

Permalink
Add Gen.subset (#451)
Browse files Browse the repository at this point in the history
* add Gen.subset (#444)

* Formatting

Co-authored-by: Jacob Stanley <[email protected]>
  • Loading branch information
chris-martin and jacobstanley committed May 22, 2022
1 parent 2e32700 commit 37dac71
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
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 @@ -1679,6 +1681,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

0 comments on commit 37dac71

Please sign in to comment.