Search code examples
haskellfunctional-programmingquickcheckproperty-based-testing

Haskell: Property Based Testing for Higher Order Function


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.


Solution

  • 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)