Write you some QuickCheck - Generating random integers
13 February 2016
This post is part of a series of posts on implementing a minimal version of QuickCheck from scratch. The source code is available on GitHub.
In the previous post I’ve generated random booleans. In this post, I’ll be generating random 32-bit signed integers.
Recall that the
Gen<'a> type is ported already in this previous post as:
This means we can write functions that handle state (—monadster!) combining:
- a size measure for data structures, i.e. list length, numbers, i.e. absolute bounds
- a pseudo-random generation seed — more about that later on
So, to generate numbers, we need:
- a generator that picks numbers with absolute value bounded by the size
- a generator that gives us the current size at runtime
Given the above, a 32-bit signed integer generator can be written as:
Here are some sample integers:
But there’s a pattern here (can you tell?); all the generated integers are in the range [-30, 30] — that’s because
generate sets the size for the generators to be up to 30.
Generating numbers in range [-999, 999]
I can run the integer generator again, but this time I’ll override the runtime size.
This prompts me to port Gen’s
Finally, here are some sample integers in the range [-999, 999]: