Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell QuickCheck minimal counter example

Consider the following tests for the distributivity law between reverse and ++,

import Test.QuickCheck

test :: [Int] -> [Int] -> Bool
test xs ys = reverse (xs ++ ys) == reverse xs ++ reverse ys

test2 :: (Eq a) => [a] -> [a] -> Bool
test2 xs ys = reverse (xs ++ ys) == reverse xs ++ reverse ys

Note for lists of Int that

*Main> quickCheck test
*** Failed! Falsifiable (after 5 tests and 3 shrinks):    
[1]
[0]

However the test for lists of equatable items,

*Main> quickCheck test2
+++ OK, passed 100 tests.

What makes the second test pass ?

Update On compiling with main = quickCheck test2, the subsequent error on ambiguous type variable hints the problem (as already depicted in answers),

No instance for (Eq a0) arising from a use of `test2'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
like image 755
elm Avatar asked Apr 08 '15 05:04

elm


2 Answers

When you actually evaluate test2, GHCi has to pick a type a to use. Without more information, GHCi's extended default rules make it default to (), for which the law is true.

like image 69
Ørjan Johansen Avatar answered Oct 20 '22 05:10

Ørjan Johansen


> verboseCheck test2 

Passed:
[]
[]
Passed:
[]
[]
Passed:
[(),()]
[()]
Passed:
[(),(),()]
[()]
Passed:
[()]
[(),(),(),()]
...

The polymorphic parameter defaults to (), and of course all such values are equal.

like image 37
András Kovács Avatar answered Oct 20 '22 05:10

András Kovács