【问题标题】:Running QuickCheck against Simple Test w/ Function针对带函数的简单测试运行 QuickCheck
【发布时间】:2015-09-22 12:11:09
【问题描述】:

鉴于以下情况:

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,即绕过或解决Int -&gt; Int 缺少的Show 实例?

【问题讨论】:

    标签: haskell quickcheck


    【解决方案1】:

    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 导入一个显示没有有用信息的虚拟实例。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-07-11
      • 2012-02-19
      相关资源
      最近更新 更多