Search code examples
haskellquickcheck

QuickCheck Generator - Arbitrary element of custom type


I am trying to generate arbitrary sized element for my custom data type:

newtype ZippList a = ZPL ([a], [a])
    deriving (Show)

This is what I got:

instance Arbitrary a => Arbitrary (ZippList a) where
arbitrary = sized zipplist where
    zipplist n = do
        firstLength <- choose(0,n)
        secondLength <- n - firstLength
        firstList <- [arbitrary :: Gen a | [1..firstLength]]
        secondList <- [arbitrary :: Gen a | [1..secondLength]]
        return $ ZPL (firstList, secondList)

However it does not compile. The compilation fails for the generation of the two lists of a. How can I generate an arbitrary a?

Damn, I kind of forgot about actually generating the values with _ <-.. Sorry for the trivial question, I was coding late hours.


Solution

  • This works for me

    instance Arbitrary a => Arbitrary (ZippList a) where
      arbitrary = sized zipplist where
        zipplist n = do
            firstLength <- choose (0, n)
            let secondLength = n - firstLength
            firstList <- sequence [arbitrary | _ <- [1..firstLength]]
            secondList <- sequence [arbitrary | _ <- [1..secondLength]]
            return $ ZPL (firstList, secondList)
    

    Note that the definition of secondLength doesn't use a monad, so you should use let