Haskell:属性 基于高阶函数的测试

Haskell: Property Based Testing for Higher Order Function

我有两个函数 foo 必须满足的属性:

prop_1 :: [Int] -> Bool
prop_1 xs = foo xs id == xs 

prop_2 :: [Int] -> (Int -> Int) -> (Int -> Int) -> Bool
prop_2 xs f g = foo (foo xs f) g == foo xs (g . f)

我正在尝试使用 quickCheck 检查上述属性是否满足以下功能:

foo :: [a] -> (a -> b) -> [b]
foo xs f = []

当我尝试 运行 使用 prop_2 进行快速检查时,出现以下错误:

quickCheck(prop_2)

<interactive>:18:1: error:
     No instance for (Show (Int -> Int))
        arising from a use of 'quickCheck'
        (maybe you haven't applied a function to enough arguments?)
     In the expression: quickCheck (prop_2)
      In an equation for 'it': it = quickCheck (prop_2)

我不确定为什么会收到此错误以及如何解决它。任何见解表示赞赏。

正如 documentation on QuickCheck 所说:

However, before we can test such a property, we must see to it that function values can be printed (in case a counter-example is found). That is, function types must be instances of class Show. To arrange this, you must import module ShowFunctions into every module containing higher-order properties of this kind. If a counter-example is found, function values will be displayed as "<function>"

所以你可以通过导入一个模块来解决这个问题:

<b>import Text.Show.Functions</b>

prop_1 :: [Int] -> Bool
prop_1 xs = foo xs id == xs 

prop_2 :: [Int] -> (Int -> Int) -> (Int -> Int) -> Bool
prop_2 xs f g = foo (foo xs f) g == foo xs (g . f)

您可以通过将 属性 更改为

来使用 QuickCheck 对 generation of random shrinkable, showable functions 的支持
prop_2 :: [Int] -> Fun Int Int -> Fun Int Int -> Bool
prop_2 xs (Fn f) (Fn g) = foo (foo xs f) g == foo xs (g . f)

然后你会看到比 <function> 更有用的反例。