quickCheck为什么创建单位列表

时间:2019-05-12 17:50:18

标签: haskell quickcheck

我尝试了QuickCheck测试一文中的以下内容,以取乐并牟利。

prop_revApp xs ys = reverse (xs ++ ys) == reverse xs ++ reverse ys

,即使它不应该通过也通过了。 我运行了verboseCheck,发现它只是检查单位列表,即:

Passed:
[(),(),(),(),(),(),(),(),(),(),(),(),(),()]

我想知道为什么会这样。

我知道可以通过定义属性的类型来修复它,但我想知道这是否有必要或我遗漏了什么。

1 个答案:

答案 0 :(得分:2)

prop_revApp函数非常通用:

*Main> :t prop_revApp
prop_revApp :: Eq a => [a] -> [a] -> Bool

如果您只是在GHCi中加载代码并运行它,是的,的确,该属性通过了:

*Main> quickCheck prop_revApp
+++ OK, passed 100 tests.

这是因为GHCi带有一组首选默认值。为了方便起见,它将尝试使用它可以使用的最简单的类型。

它并没有比()简单得多,并且由于()有一个Eq实例,因此可以选择它。

另一方面,如果您实际上尝试编写和编译某些属性,则代码不会编译:

import Test.Framework (defaultMain, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)

import Test.QuickCheck

main :: IO ()
main = defaultMain tests

prop_revApp xs ys = reverse (xs ++ ys) == reverse xs ++ reverse ys

tests = [
        testGroup "Example" [
                testProperty "prop_revApp" prop_revApp
           ]
      ]

如果尝试使用stack test运行这些测试,则会出现编译器错误:

test\Spec.hs:11:17: error:
    * Ambiguous type variable `a0' arising from a use of `testProperty'
      prevents the constraint `(Arbitrary a0)' from being solved.
      Probable fix: use a type annotation to specify what `a0' should be.
      These potential instances exist:
        instance (Arbitrary a, Arbitrary b) => Arbitrary (Either a b)
          -- Defined in `Test.QuickCheck.Arbitrary'
        instance Arbitrary Ordering
          -- Defined in `Test.QuickCheck.Arbitrary'
        instance Arbitrary Integer
          -- Defined in `Test.QuickCheck.Arbitrary'
        ...plus 19 others
        ...plus 61 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    * In the expression: testProperty "prop_revApp" prop_revApp
      In the second argument of `testGroup', namely
        `[testProperty "prop_revApp" prop_revApp]'
      In the expression:
        testGroup "Example" [testProperty "prop_revApp" prop_revApp]
   |
11 |                 testProperty "prop_revApp" prop_revApp
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

您必须为属性指定一个更具体的类型;例如

tests = [
        testGroup "Example" [
                testProperty "prop_revApp" (prop_revApp :: [Int] -> [Int] -> Bool)
           ]
      ]

现在测试可以编译,但是失败:

$ stack test
Q56101904-0.1.0.0: test (suite: Q56101904-test)

Example:
  prop_revApp: [Failed]
*** Failed! Falsifiable (after 3 tests and 3 shrinks):
[1]
[0]
(used seed -7398729956129639050)

         Properties  Total
 Passed  0           0
 Failed  1           1
 Total   1           1

Q56101904-0.1.0.0: Test suite Q56101904-test failed
Test suite failure for package Q56101904-0.1.0.0
    Q56101904-test:  exited with: ExitFailure 1
Logs printed to console