[英]How can I constraint QuickCheck parameters, e.g. only use non-negative ints?
我是Haskell的新手。 到目前为止,这是非常好的,但我正在尝试复制粘贴我的QuickCheck属性,我想解决这个问题。
这是一个简单的例子:
prop_Myfunc :: [Int] -> (Int,Int) -> Bool
prop_Myfunc ints (i,j) = ints !! i == ints !! j
这不起作用,因为QuickCheck生成负数,所以我得到
*** Failed! (after 2 tests and 2 shrinks):
Exception:
Prelude.(!!): negative index
我试图谷歌寻求解决方案,我发现例如NonNegative和==>,但我不明白它们是如何工作的。
我怎样才能限制上面的例子,以便i和j永远不会消极? 而且,既不是太高了? 即: 0 <= i,j < length ints
首先,请参阅此SO答案 ,了解如何编写自定义Gen ...
函数以及如何使用forAll
组合器的forAll
。
以下是如何为列表中的非空列表和两个有效的非负索引编写生成器:
import Test.QuickCheck
genArgs :: Gen ( [Int], Int, Int )
genArgs = do
x <- arbitrary
xs <- arbitrary
let n = length xs
i <- choose (0,n)
j <- choose (0,n)
return ( (x:xs), i, j) -- return a non-empty list
test = quickCheck $ forAll genArgs $ \(xs,i,j) -> prop_myfunc xs (i,j)
约束包装器(来自Test.QuickCheck.Modifiers
,如果它们不是隐式Test.QuickCheck.Modifiers
)可以这样使用:
prop_Myfunc :: [Int] -> (NonNegative Int, NonNegative Int) -> Bool
prop_Myfunc ints (NonNegative i, NonNegative j) = ints !! i == ints !! j
你可以把SomeWrapper a
作为a
具有修改的分布。 例如, NonNegative a
确保a >= 0
。 生成包装器后,可以使用模式匹配或显式访问器(在本例中为getNonNegative
)获取值。
至于约束索引的上边距,我认为使用包装器是不可能的(在Haskkell类型系统中不可能使用值参数化类型,在这种情况下是列表长度)。 但是,使用==>
运算符,您可以为测试添加任意布尔约束:
prop_Myfunc ints (NonNegative i, NonNegative j) = i < l && j < l ==> ints !! i == ints !! j where
l = length ints
它以其他方式工作:当条件不成立时,它只是丢弃当前的测试用例。 但要小心:如果抛出的案例太多(条件限制太多),那么测试就变得不那么有用了。 通过shrink
测试数据通常可以实现“无损”行为,但这是另一个主题。
我遇到了与你类似的情况,我终于找到了如何使用==>
这里: http : //www.cse.chalmers.se/~rjmh/QuickCheck/manual.html ,在“条件属性”部分。
在您的示例中,您必须使用Property
替换Bool
并在属性测试之前插入有关变量的要求,如下所示:
prop_Myfunc :: [Int] -> (Int,Int) -> Property
prop_Myfunc ints (i,j) = (i >= 0 && j >= 0) ==> ints !! i == ints !! j
(我没有对这个特定的例子进行过测试,但是对于类似的情况,它对我有用。)
注意类型==>
:( (==>) :: Testable prop => Bool -> prop -> Property
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.