Search code examples
haskelltypesquickcheck

How do I constrain QuickCheck when using type synonyms?


I am using QuickCheck to run arbitrary test cases on my code. However, in one portion of my code I have the type synonym:

type Vector = [Double]

I also have a few functions that accept a number of Vectors as input. However, all of these functions require that the Vectors be of the same length.

Is there a way to constrain QuickCheck so that it only generates lists of length n?


Solution

  • A simple solution is to not have an arbitrary instance but instead to do something like

    import Test.QuickCheck
    import Control.Monad
    
    prop_vec :: Int -> Gen [Double]
    prop_vec = flip replicateM arbitrary . abs
    
    
    prop_addComm :: Int -> Gen Bool
    prop_addComm i  = do
      v <- prop_vec i
      u <- prop_vec i
      return $ u + v = v + u --assuming you'd added a Num instance for your vectors
    

    There's never a typeclass so you get less helpful failures, but it's simpler to whip up.