HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Modulegeneric-arbitrary-1.0.1Haskell2010

Test.QuickCheck.Arbitrary.Generic

This module is a generic implementation of the arbitrary method. Example usage:

data Foo = Foo
  { _fooX :: X
  , _fooY :: Y
  } deriving (Generic)

instance Arbitrary Foo where
  arbitrary = genericArbitrary
  shrink = genericShrink

This instance can also be derived using DerivingVia language extension

data Foo = Foo
  { _fooX :: X
  , _fooY :: Y
  } deriving (Generic)
    deriving (Arbitrary) via GenericArbitrary Foo

The generated arbitrary method is equivalent to

Foo <$> arbitrary <*> arbitrary

.

It can also handle a recursive types problem. Assuming a type

data R = R R
  deriving Generic

there is no instance

instance Arbitrary R where
  arbitrary = genericArbitrary
  shrink = genericShrink

If you try to compile this you will get a type level error

   • R refers to itself in all constructors

Which means that there is no finite term for R because it is recursive. But, if you correct the definition of R like this.

data R = R R | F
  deriving Generic

Then it will compile. And the arbitrary generated will not hang forever, because it respects the size parameter.

There is a limitation of recursion detection:

data R1 = R1 R2
  deriving (Eq, Ord, Show, Generic)
  deriving anyclass NFData
  deriving Arbitrary via (GenericArbitrary R1)

data R2 = R2 R1
  deriving (Eq, Ord, Show, Generic)
  deriving anyclass NFData
  deriving Arbitrary via (GenericArbitrary R2)

This code will compile and the arbitrary generated will always hang. Yes, there is a problem with mutually recursive types.

Now lets see an example of datatype with parameters

data A a = A a
  deriving (Eq, Ord, Show)
  deriving anyclass NFData
  deriving (Generic)

instance (Arbitrary a) => Arbitrary (A a) where
  arbitrary = genericArbitrary
  shrink = genericShrink

It should work from first glance, but when compile it will throw an error:

    • Could not deduce (Test.QuickCheck.Arbitrary.Generic.GArbitrary
                          (A a)
                          (GHC.Generics.D1
                             ('GHC.Generics.MetaData A ParametersTest "main" 'False)
                             (GHC.Generics.C1
                                ('GHC.Generics.MetaCons A 'GHC.Generics.PrefixI 'False)
                                (GHC.Generics.S1
                                   ('GHC.Generics.MetaSel
                                      'Nothing
                                      'GHC.Generics.NoSourceUnpackedness
                                      'GHC.Generics.NoSourceStrictness
                                      'GHC.Generics.DecidedLazy)
                                   (GHC.Generics.Rec0 a))))
                          (TypesDiffer (A a) a))
        arising from a use of ‘genericArbitrary’

Here the TypesDiffer is a type familty dealing with recursive types and helping us to eliminate inproper instances. To convince the compiller, that the a parameter is not an A a we must fix the instance with additional constraint

instance (Arg (A a) a, Arbitrary a) => Arbitrary (A a) where
  arbitrary = genericArbitrary
  shrink = genericShrink

Now everything compiles and works as expected.

  • 2 types
  • 4 classes
  • 2 values

Main

3 declarations
newtypenewtype GenericArbitrary a
#

Newtype for DerivingVia

Usage:

data Foo = Foo
  { _fooX :: X
  , _fooY :: Y
  } deriving (Generic)
    deriving (Arbitrary) via GenericArbitrary Foo
Instances3Eq, Show, Arbitrary
typetype Arg (self :: k) (field :: k) = TypesDiffer self field ~ 'True
#

Constraint helper for types with parameters

Usage:

data A a = A a
  deriving (Generic)
instance (Arg (A a) a, Arbitrary a) => Arbitrary (A a) where
  arbitrary = genericArbitrary
  shrink = genericShrink

Internal

8 declarations
classclass Finite self a ~ finite => GArbitrary self (a :: Type -> Type) (finite :: Bool) where
#

Generic arbitrary.

Parameters are: * self: the ADT we generating instance for * a: some part of the `Rep self` * finite: Is a finite? Infinite type has no finite values (like Stream)

Instances10GArbitrary, …
classclass (Finite self a ~ af, Finite self b ~ bf) => FiniteSum self (a :: Type -> Type) (b :: Type -> Type) (af :: Bool) (bf :: Bool) where
#
Instances3FiniteSum

Reexports

2 declarations
classclass Arbitrary a where
#

Random generation and shrinking of values.

QuickCheck provides Arbitrary instances for most types in base, except those which incur extra dependencies. For a wider range of Arbitrary instances see the quickcheck-instances package.

Methods

  • arbitrary :: Gen a

    A generator for values of the given type.

    It is worth spending time thinking about what sort of test data you want - good generators are often the difference between finding bugs and not finding them. You can use sample, label and classify to check the quality of your test data.

    There is no generic arbitrary implementation included because we don't know how to make a high-quality one. If you want one, consider using the testing-feat or generic-random packages.

    The QuickCheck manual goes into detail on how to write good generators. Make sure to look at it, especially if your type is recursive!

  • shrink :: a -> [a]

    Produces a (possibly) empty list of all the possible immediate shrinks of the given value.

    The default implementation returns the empty list, so will not try to shrink the value. If your data type has no special invariants, you can enable shrinking by defining shrink = genericShrink, but by customising the behaviour of shrink you can often get simpler counterexamples.

    Most implementations of shrink should try at least three things:

    1. Shrink a term to any of its immediate subterms. You can use subterms to do this.

    2. Recursively apply shrink to all immediate subterms. You can use recursivelyShrink to do this.

    3. Type-specific shrinkings such as replacing a constructor by a simpler constructor.

    For example, suppose we have the following implementation of binary trees:

    data Tree a = Nil | Branch a (Tree a) (Tree a)

    We can then define shrink as follows:

    shrink Nil = []
    shrink (Branch x l r) =
      -- shrink Branch to Nil
      [Nil] ++
      -- shrink to subterms
      [l, r] ++
      -- recursively shrink subterms
      [Branch x' l' r' | (x', l', r') <- shrink (x, l, r)]

    There are a couple of subtleties here:

    • QuickCheck tries the shrinking candidates in the order they appear in the list, so we put more aggressive shrinking steps (such as replacing the whole tree by Nil) before smaller ones (such as recursively shrinking the subtrees).

    • It is tempting to write the last line as [Branch x' l' r' | x' <- shrink x, l' <- shrink l, r' <- shrink r] but this is the wrong thing! It will force QuickCheck to shrink x, l and r in tandem, and shrinking will stop once one of the three is fully shrunk.

    There is a fair bit of boilerplate in the code above. We can avoid it with the help of some generic functions. The function genericShrink tries shrinking a term to all of its subterms and, failing that, recursively shrinks the subterms. Using it, we can define shrink as:

    shrink x = shrinkToNil x ++ genericShrink x
      where
        shrinkToNil Nil = []
        shrinkToNil (Branch _ l r) = [Nil]

    genericShrink is a combination of subterms, which shrinks a term to any of its subterms, and recursivelyShrink, which shrinks all subterms of a term. These may be useful if you need a bit more control over shrinking than genericShrink gives you.

    A final gotcha: we cannot define shrink as simply shrink x = Nil:genericShrink x as this shrinks Nil to Nil, and shrinking will go into an infinite loop.

    If all this leaves you bewildered, you might try shrink = genericShrink to begin with, after deriving Generic for your type. However, if your data type has any special invariants, you will need to check that genericShrink can't break those invariants.

Instances115Arbitrary, …