假设我想为(!!)
函数编写一些单元测试。
my_prop xs n = ...
我希望将n限制为仅有效的索引,并且我知道我可以这样做
my_prop xs n = (not.null) (drop n xs) ==> ...
但这使得绝大多数生成的案例都是无效的,并被丢弃。有没有一种方法可以让QuickCheck首先生成xs
列表,然后使用它的值只生成有效的n
案例
发布于 2012-10-11 04:46:55
发布于 2012-10-11 04:46:35
您可以创建一个只创建有效索引的生成器,并将您的属性写成
import Test.QuickCheck
import Test.QuickCheck.Gen
import System.Random
indices :: [a] -> Gen Int
indices xs = MkGen $ \sg _ -> fst $ randomR (0, length xs - 1) sg
my_prop :: [Char] -> Property
my_prop xs = not (null xs) ==> forAll (indices xs) (\i -> xs !! i /= '0')
消除Int
参数。
发布于 2012-10-12 03:58:34
正如Daniel Wagner所建议的,一种可能性是创建我自己的数据类型并为其提供一个Arbitrary
实例。
data ListAndIndex a = ListAndIndex [a] Int deriving (Show)
instance Arbitrary a => Arbitrary (ListAndIndex a) where
arbitrary = do
(NonEmpty xs) <- arbitrary
n <- elements [0..(length xs - 1)]
return $ ListAndIndex xs n
NonEmpty
来自Test.QuickCheck.Modifiers
中用于生成非空列表的自定义类型。
https://stackoverflow.com/questions/12827861
复制相似问题