我正在尝试为自定义数据类型生成任意大小的元素:
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?
该死的,我有点忘了用_ <-
实际生成这些值。抱歉这个琐碎的问题,我编码很晚。
答案 0 :(得分:2)
这对我有用
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