Search code examples
haskellquickcheck

How to generate specific random string in QuickCheck?


In Haskell's QuickCheck, how to generate a string such that it contains only the characters ‘S’ and ‘C’, and the position of ‘S’ and ‘C’ is random?

For example: "SCCS", "SSSS", "CCCC", "CSSCCS", ""

My use case is this:

I have two functions countCAndS :: String -> (Int, Int) and countCAndS' :: String -> (Int, Int). They have the same type signature. I'd like to write a QuickCheck property such that I can pass the same string to these two different functions and check if the outputs are the same.


Solution

  • QuickCheck provides a flurry of combinators for that, it's super easy and very elegant:

    prop_CountersEqual = 
      forAll csString $ \s -> countCAndS s == countCAndS' s
    
    csString :: Gen String
    csString = listOf $ elements "CS"
    

    It's also trivial to expand your dictionary, should you need it.