Kev*_*ith 7 haskell quickcheck
鉴于以下内容:
test :: (Int -> Int) -> Int -> Bool
test _ _ = True
Run Code Online (Sandbox Code Playgroud)
编译源代码后,我尝试运行quickCheck test:
> quickCheck test
<interactive>:27:1:
No instance for (Show (Int -> Int))
arising from a use of ‘quickCheck’
In the expression: quickCheck test
In an equation for ‘it’: it = quickCheck test
Run Code Online (Sandbox Code Playgroud)
看看这个函数的Show实例,我觉得不存在这样的实例.
我该如何运行quickCheck test,即绕过或解决丢失的Show实例Int -> Int?
QuickCheck有一个特殊的模块,Test.QuickCheck.Function用于生成可以显示的"功能"(也是"缩小",这是QuickCheck简化其反例的方式).您可以使用它们将它们转换为普通函数apply.例如,如果您有该文件:
import Test.QuickCheck
import Test.QuickCheck.Function
test :: Fun Int Int -> Int -> Bool
test _ _ = True
test2 :: Fun Int Int -> Int -> Bool
test2 f x = apply f x == x
Run Code Online (Sandbox Code Playgroud)
然后在GHCi中:
*Main> quickCheck test
+++ OK, passed 100 tests.
*Main> quickCheck test2
*** Failed! Falsifiable (after 2 tests and 3 shrinks):
{_->0}
1
Run Code Online (Sandbox Code Playgroud)
它是实际上可以定义一个Show实例函数本身,并使用它.但除非你的输入类型是有限类型Bool,否则你将无法以这种方式打印有关函数的所有信息.您可以导入一个不显示有用信息的虚拟实例Text.Show.Functions.
但是,Test.QuickCheck.Function.Fun上面使用的类型看起来像是为了更简洁地提供基本信息,所以如果可能的话,我当然会自己使用它.