[Haskell-cafe] [ANN] generic-random-0.2.0.0
Li-yao Xia
li-yao.xia at ens.fr
Tue Aug 16 21:26:41 UTC 2016
Hello,
This library aims to derive random generators for ADTs. The previous and
first release was an implementation of Boltzmann generators, in response
to this blogpost by Brent Yorgey.
https://byorgey.wordpress.com/2016/03/23/boltzmann-sampling-for-generic-arbitrary-instances/
It's nice to look at, but it is an opinionated choice about the
resulting probability distribution which is not always suitable.
In this release, using GHC.Generics, Generic.Random.Generic wraps common
boilerplate to define "arbitrary" in particular, hiding from you long
chains of the following:
Constructor <$> arbitrary <*> arbitrary <*> arbitrary
as well as
frequency [(n1, C1 <$> arbitrary), (n2, C2 <$> arbitrary), ...]
leaving just the weights [n1, n2, ...] for you to specify.
data Tree a = Leaf a | Node (Tree a) (Tree a)
deriving Generic
instance Arbitrary a => Arbitrary (Tree a) where
arbitrary = genericArbitraryFrequency [9, 8]
-- equivalent to
-- > arbitrary = frequency
-- > [ (9, Leaf <$> arbitrary)
-- > , (8, Node <$> arbitrary <*> arbitrary)
-- > ]
It comes with a simple opt-in strategy to bound the size of generated
data, especially convenient for recursive data types. Indeed, even for a
simple binary tree, the naive generator obtained by producing a leaf
half of the times, and an inner node the other half, with two
recursively generated children, results in a random tree of *infinite*
expected size (though the tree is still "almost surely" finite).
There is no theoretical reason the library uses two flavors of generics
for different tasks. There are trade-offs, but I can't see impassable
obstacles to use one in place of the other. If I had to be consistent
now I'd choose GHC.Generics, though I was not fluent enough in that
flavor at the time when I wrote the Data part.
Property-based testing is the main application I have in mind for this
library. Nevertheless, I welcome ideas, questions and suggestions from
any domain or of general nature.
Github: https://github.com/lysxia/generic-random
Hackage: http://hackage.haskell.org/package/generic-random
Li-yao
More information about the Haskell-Cafe
mailing list