I have two function. One is implemented using patterns and the other using intensive lists. I want to check if the result is the same always with QickCheck.
pares xs = [a | a <- xs , mod a 2 == 0]
cuadrados xs = [x^2 | x <- pares xs ]
cuadrados'' [] = []
cuadrados'' (x:xs) = [x^2] ++ cuadrados'' xs
cuadrados' (x:xs) = cuadrados'' (pares (x:xs))
Im trying:
prop_cuadrados xs = cuadrados xs == cuadrados' xs
When I try quickCkeck prop_cuadrados the output is the following:
*Main> quickCheck prop_cuadrados *** Failed! (after 1 test): Exception: sesion4.hs:10:1-47: Non-exhaustive patterns in function cuadrados' []
How can I solve this problem? Thanks
We can find that problem immediately if we either apply -Wall
in GHC (which automatically enables -Wincomplete-patterns
) or just try the found counter example by hand.
QuickCheck finds xs = []
as counterexample. So let us have a look at cuadrados'
:
cuadrados' []
At that point, we cannot continue, as cuadrados'
only binds on a single pattern: (x:xs)
. Unfortunately, []
cannot match that pattern and you end up with an error. To fix it, simply add another pattern:
cuadrados' [] = []
cuadrados' (x:xs) = …
or just use
cuadrados' xs = cuadrados'' (pares xs)
as we don't use the first element explicitly.
That being said, pares
is filter even
, and cuadrados
is map (^2) . filter even
map (^2) . filter even
. Try to use the standard library and higher order functions a little bit more.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.