Using QuickCheck with Custom Data Types

QuickCheck is awesome! But trying to figure out how to use it with custom data types could be hard for newbies like me. The documentation assumes that you are already fluent in Haskell and hardly provides explanations or code snippets. Hopefully, the following two examples will give you a glimpse of the syntax and help you make your way out of the numerous compiler errors.

Let’s start with defining a simple data type Point that holds two Int values:

module QCSamples where
import Test.QuickCheck

data Point = Pt Int Int

instance Show (Point) where 
  show (Pt x y) = "{" ++ show x ++ "," ++ show y ++ "}"

To use the Point data type in QuickCheck, we need to provide an implementation of Arbitrary:

instance Arbitrary Point where
   arbitrary = do
     x <- arbitrary
     y <- arbitrary
     return $ Pt x y

Note that in the above example we only need to say x<-arbitrary and y<-arbitrary to get the random Ints. Haskell will infer their type from the specification of Point and will provide the appropriate arbitrary implementation, i.e. Int. So, now we can let QuickCheck produce random Points.

*QCSamples> sample $ (arbitrary :: Gen Point)

Now, let's have a look at a slightly harder example:

data Set a = Set [a]

instance (Show a) => Show (Set a) where
     show s = showSet s where
          showSet (Set []) = "{}"
          showSet (Set (x:xs)) = "{" ++ show x ++ showSubSet xs ++ "}" where
               showSubSet [] = ""
               showSubSet (x:xs) = "," ++ show x ++ showSubSet xs

Here is the implementation of Arbitrary that will allow us to use the Set type in QuickCheck:

instance (Arbitrary a) => Arbitrary (Set a) where
    arbitrary = do
                list <- arbitrary
                return $ Set list

Note that this time we have to have the typeclass (Arbitrary a) in the definition. With this addition we can create Sets of anything that provides implementation for Arbitrary, e.g. Set Int, Set String and Set Point!

*QCSamples> sample $ (arbitrary :: Gen (Set Int))
*QCSamples> sample $ (arbitrary :: Gen (Set Point))

Leave a Reply

Your email address will not be published. Required fields are marked *