Non-exhaustive templates in functions defined in GHCi
I am trying to write a sieve from the Erasthosthenes function that gives the user all the Primes from 2 to its upper limit. So I wrote this code:
main = do
putStrLn "Upper Limit"
g <- readLn
let sieve [] = []
let sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
let primes = sieve [2..g]
print primes
The code compiles and gives me the correct solution, but I get this exception at the end of the solution: *** Exception: Non-Exhaustive Patterns in Lattice Sieve So I checked which patterns don't match.
warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for `sieve': Patterns not matched: (_:_)
warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for `sieve': Patterns not matched: []
Which I don't understand, since I gave let sieve [] = []
And I thought _ in Haskell means any variable, so what does the (:) pattern mean? Any help would be appreciated.
source to share
The problem is what you define sieve
in two separate statementslet
. As a result, the Haskell compiler thinks that you are defining two separate functionssieve
. Therefore, the former is sieve
missing a template (_:_)
and the latter is a template []
.
If you use later sieve
, the Haskell compiler will refer to the closest one, so the last one (as a result of the call sieve
) in it let primes = sieve [2..g]
will only know about the second definition sieve
and therefore will be an error at the end of the list).
You can solve this problem using the following operator let
:
let { sieve [] = [] ; sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0] }
source to share