QuickCheck 生成器 - 自定义类型的任意元素

QuickCheck Generator - Arbitrary element of custom type

我正在尝试为我的自定义数据类型生成任意大小的元素:

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

这是我得到的:

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)

但是它不编译。生成 a 的两个列表时编译失败。如何生成任意 a?

该死,我有点忘了用 _ <- 实际生成值了。抱歉这个小问题,我编码到很晚了。

这对我有用

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)

注意 secondLength 的定义没有使用 monad,所以你应该使用 let