如何在main中使用quickcheck

mat*_*tio 4 haskell quickcheck

我正在为我编写的二进制搜索函数编写测试。

module Tests where

import Data.List (sort)
import Test.QuickCheck
import BinarySearch (binarySearch)

prop_equals_elem x xs = (binarySearch x $ sort xs) == (x `elem` xs)

args = Args {replay = Nothing, maxSuccess = 200, maxDiscard=200, maxSize=200, chatty = False}

main = do
    quickCheck (prop_equals_elem :: (Ord a) => a -> [a] -> Bool)
Run Code Online (Sandbox Code Playgroud)

在 ghci 中使用 quickCheck 效果很好,但是当我尝试运行 main 时,它给出了错误

Tests.hs:12:5:
    Ambiguous type variable `a0' in the constraints:
      (Arbitrary a0) arising from a use of `quickCheckWith'
          at Tests.hs:12:5-18
      (Show a0) arising from a use of `quickCheckWith'
          at Tests.hs:12:5-18
      (Ord a0) arising from an expression type signature
          at Tests.hs:12:26-72
Run Code Online (Sandbox Code Playgroud)

为什么这在 main 中不起作用,但在 ghci 中起作用?

ham*_*mar 5

这可能是由GHCi 中扩展默认规则引起的。

在测试这样的函数时,您需要使用具体的元素类型。()由于扩展规则,GHCi 会默认元素类型为,但是在正常编译代码时不会发生这种情况,因此 GHC 告诉您它无法确定使用哪种元素类型。

例如,您可以使用它Int来代替测试。()对于测试此功能非常无用,因为所有元素都相同。

quickCheck (prop_equals_elem :: Int -> [Int] -> Bool)
Run Code Online (Sandbox Code Playgroud)

如果它适用于Int,则由于参数化,它应该适用于任何类型。