Skip to content

Commit bf0b5fb

Browse files
Use NonEmptyArray rather than NEL for frequency (#131)
* Use NonEmptyArray rather than NEL for frequency * Add changelog
1 parent 76b7beb commit bf0b5fb

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ Notable changes to this project are documented in this file. The format is based
66

77
Breaking changes:
88
- Migrate FFI to ES modules (#130 by @kl0tl and @JordanMartinez)
9+
- Make `frequency` use `NonEmptyArray` (#131 by @JordanMartinez)
10+
11+
Now `oneOf` and `frequency` both use `NonEmptyArray` rather than `NonEmptyList`.
912

1013
New features:
1114

src/Test/QuickCheck/Gen.purs

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,10 @@ import Data.Array ((:), length, zip, sortBy)
4444
import Data.Array.NonEmpty (NonEmptyArray)
4545
import Data.Array.NonEmpty as NEA
4646
import Data.Enum (class BoundedEnum, fromEnum, toEnum)
47-
import Data.Foldable (fold)
47+
import Data.Semigroup.Foldable (foldMap1)
4848
import Data.Int (toNumber, floor)
4949
import Data.List (List(..), toUnfoldable)
50-
import Data.List.NonEmpty (NonEmptyList)
51-
import Data.List.NonEmpty as NEL
52-
import Data.Maybe (fromJust)
50+
import Data.Maybe (Maybe(..), fromJust)
5351
import Data.Monoid.Additive (Additive(..))
5452
import Data.Newtype (unwrap)
5553
import Data.Tuple (Tuple(..), fst, snd)
@@ -162,15 +160,19 @@ oneOf xs = do
162160

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

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

0 commit comments

Comments
 (0)