-1

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.

VSZM
  • 1,341
  • 2
  • 17
  • 31

1 Answers1

2

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

jamshidh
  • 12,002
  • 17
  • 31
  • `sequence [arbitrary | _ <- [1..firstLength]]` looks a lot like `replicateM firstLength arbitrary` to me! – epsilonhalbe Apr 27 '16 at 12:19
  • 1
    @epsilonhalbe I also prefer your way, but the comprehensions approach seems to be idiomatic in quickstart for some reason, see https://www.schoolofhaskell.com/user/griba/quick-check-generator-of-pair-List-index-where-index-within-list-range – jamshidh Apr 27 '16 at 15:38
  • Damn, I kind of forgot about actually generating the values with `_ <-`.. Sorry for the trivial question, I was coding late hours. Thanks for the answer anyway. – VSZM Apr 27 '16 at 17:05