针对具有功能的简单测试运行QuickCheck

时间:2015-09-22 02:27:38

标签: haskell quickcheck

鉴于以下内容:

test :: (Int -> Int) -> Int -> Bool
test _ _ = True

编译源代码后,我尝试运行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

看一下这个Show instance for functions,我觉得不存在这样的实例。

如何运行quickCheck test,即绕过或解决Show丢失的Int -> Int个实例?

1 个答案:

答案 0 :(得分:8)

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

然后在GHCi中:

*Main> quickCheck test
+++ OK, passed 100 tests.
*Main> quickCheck test2
*** Failed! Falsifiable (after 2 tests and 3 shrinks): 
{_->0}
1

实际上可以为函数本身定义Show实例,并使用它。但除非您的输入类型是像Bool这样的有限类型,否则您将无法以这种方式打印有关函数的所有信息。您可以从Text.Show.Functions导入显示 no 有用信息的虚拟实例。

但是,上面使用的Test.QuickCheck.Function.Fun类似乎是为了更简洁地提供基本信息,所以如果可能的话,我当然会自己使用它。

相关问题