2015-04-08 19 views
9

Si consideri il seguente test per la distributivity law between reverse and ++,Haskell QuickCheck minimo contatore esempio

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 

Nota per gli elenchi di Int che

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

Tuttavia il test di elenchi di elementi equatable,

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

Cosa fa passare il secondo test?

Aggiornamento Su compilazione con main = quickCheck test2, il successivo errore variabile di tipo ambiguo allude il problema (come già descritto nelle risposte),

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) 

risposta

14

Quando in realtà valutare test2, GHCi deve scegliere un tipo di a usare. Senza ulteriori informazioni, le regole predefinite estese di GHCi la rendono predefinita su (), per cui la legge è vera.

13
> verboseCheck test2 

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

I polimorfici parametro imposta automaticamente (), e naturalmente tutti questi valori sono uguali.