Haskell: Property Based Testing for Higher Order Function

痴心易碎 提交于 2019-12-11 05:13:38

问题


I have two properties that a function foo must satisfy:

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)

I am trying to check whether the above properties satisfy the following function using quickCheck:

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

When I tried running quickCheck with prop_2 I get the following error:

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)

I am not sure why I am getting this error and how I can resolve it. Any insights are appreciated.


回答1:


As the documentation on QuickCheck says:

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>"

So you can fix this by importing a module like:

import Text.Show.Functions

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)



回答2:


You can use QuickCheck's support for generation of random shrinkable, showable functions by changing the property to

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)

and then you'll see something more useful than <function> for counterexamples.



来源:https://stackoverflow.com/questions/56805030/haskell-property-based-testing-for-higher-order-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!