Search code examples
listfunctionhaskelllist-comprehension

"Pattern match is redundant" when using input list argument inside list comprehension


This is my code:

example = [1,-4,7,12]

positiveSum :: [Int] -> Int
positiveSum (x) = 0
positiveSum (x:xs) = result
  where 
    result = sum [y+y | y <- xs, y > 0]

main = do
  print (positiveSum example)

When I run it I get:

Main.hs:5:1: warning: [-Woverlapping-patterns]
    Pattern match is redundant
    In an equation for `positiveSum': positiveSum (x : xs) = ...
  |
5 | positiveSum (x:xs) = result
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^...

I can't use 'xs' inside the list comprehension and I don't understand why. It's a reference, and I should be able to use it. Why is it redundant?

Edit:

The answer solved the problem, I was matching anything with the first (x). Also, I confused myself and was applying sum twice. This is the right code:

positiveSum :: [Int] -> Int
positiveSum [] = 0
positiveSum xs = result
  where 
    result = sum [x | x <- xs, x > 0]

Solution

  • You seem to think positiveSum (x) = 0 will only match the case of an empty list, but that will in fact match anything, which makes the next line redundant since it will never get tried. You meant to write positiveSum [] = 0 there. Also, note that your second case, even though it will now run, will throw away the head of the list, which you probably didn't mean to do.