Skip to content

Commit c17dc11

Browse files
authored
Merge pull request #4 from purescript/nonempty
Add a generator for `NonEmpty` values
2 parents e57232c + 6db517e commit c17dc11

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/Control/Monad/Gen/Common.purs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,15 @@ module Control.Monad.Gen.Common where
33
import Prelude
44

55
import Control.Apply (lift2)
6-
import Control.Monad.Gen (class MonadGen, choose, chooseFloat)
6+
import Control.Monad.Gen (class MonadGen, resize, choose, chooseFloat, unfoldable)
7+
import Control.Monad.Rec.Class (class MonadRec)
78

89
import Data.Either (Either(..))
910
import Data.Identity (Identity(..))
1011
import Data.Maybe (Maybe(..))
12+
import Data.NonEmpty (NonEmpty, (:|))
1113
import Data.Tuple (Tuple(..))
14+
import Data.Unfoldable (class Unfoldable)
1215

1316
-- | Creates a generator that outputs `Either` values, choosing a value from a
1417
-- | `Left` or the `Right` with even probability.
@@ -34,3 +37,18 @@ genMaybe gen = do
3437
-- | pair of generators for each slot in the tuple.
3538
genTuple :: forall m a b. Apply m => m a -> m b -> m (Tuple a b)
3639
genTuple = lift2 Tuple
40+
41+
-- | Creates a generator that outputs `NonEmpty` values, choosing values from a
42+
-- | generator for each of the items.
43+
-- |
44+
-- | The size of the value will be determined by the current size state
45+
-- | for the generator. To generate a value of a particular size, use the
46+
-- | `resize` function from the `MonadGen` class first.
47+
genNonEmpty
48+
:: forall m a f
49+
. MonadRec m
50+
=> MonadGen m
51+
=> Unfoldable f
52+
=> m a
53+
-> m (NonEmpty f a)
54+
genNonEmpty gen = (:|) <$> gen <*> resize (_ - 1) (unfoldable gen)

0 commit comments

Comments
 (0)