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

Use NonEmptyArray rather than NEL for frequency #131

Merged
merged 2 commits into from
Mar 16, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ Notable changes to this project are documented in this file. The format is based

Breaking changes:
- Migrate FFI to ES modules (#130 by @kl0tl and @JordanMartinez)
- Make `frequency` use `NonEmptyArray` (#131 by @JordanMartinez)

Now `oneOf` and `frequency` both use `NonEmptyArray` rather than `NonEmptyList`.

New features:

Expand Down
24 changes: 13 additions & 11 deletions src/Test/QuickCheck/Gen.purs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,10 @@ import Data.Array ((:), length, zip, sortBy)
import Data.Array.NonEmpty (NonEmptyArray)
import Data.Array.NonEmpty as NEA
import Data.Enum (class BoundedEnum, fromEnum, toEnum)
import Data.Foldable (fold)
import Data.Semigroup.Foldable (foldMap1)
import Data.Int (toNumber, floor)
import Data.List (List(..), toUnfoldable)
import Data.List.NonEmpty (NonEmptyList)
import Data.List.NonEmpty as NEL
import Data.Maybe (fromJust)
import Data.Maybe (Maybe(..), fromJust)
import Data.Monoid.Additive (Additive(..))
import Data.Newtype (unwrap)
import Data.Tuple (Tuple(..), fst, snd)
Expand Down Expand Up @@ -162,15 +160,19 @@ oneOf xs = do

-- | Create a random generator which selects and executes a random generator from
-- | a non-empty, weighted list of random generators.
frequency :: forall a. NonEmptyList (Tuple Number (Gen a)) -> Gen a
frequency = NEL.uncons >>> \{ head: x, tail: xs } -> let
xxs = Cons x xs
total = unwrap $ fold (map (Additive <<< fst) xxs :: List (Additive Number))
pick _ d Nil = d
pick n d (Cons (Tuple k x') xs') = if n <= k then x' else pick (n - k) d xs'
frequency :: forall a. NonEmptyArray (Tuple Number (Gen a)) -> Gen a
frequency xxs =
let
default = snd $ NEA.head xxs
total = unwrap $ foldMap1 (Additive <<< fst) xxs
pick i n = case NEA.index xxs i of
Nothing -> default
Just (Tuple k x')
| n <= k -> x'
| otherwise -> pick (i + 1) (n - k)
in do
n <- choose zero total
pick n (snd x) xxs
pick 0 n

-- | Create a random generator which generates an array of random values.
arrayOf :: forall a. Gen a -> Gen (Array a)
Expand Down