1

This is my sumEvenOdd function that takes a list of numbers. It returns a tuple of two numbers: the sum of the even-index items in the given list, and the sum of the odd-index items. Indices are zero-based.

sumEvenOdd :: Num a => [a] -> (a, a)
sumEvenOdd (x:xs) = ((foldl1 (+) (evens(xs))), (foldl1 (+) (odds(xs)))) where
evens (x:xs) = x:odds xs
odds (_:xs) = evens xs

To get my odds I just skip a spot

If I call sumEvenOdd [1,2,3,4] should return (4,6) or, sumEvenOdd [] should return (0,0).

But I get " Exception:Non-exhaustive patterns in function odds "

I just don't see where the redundant pattern is.

  • 4
    your `evens` and `odds` do not take into account the empty list. – Willem Van Onsem Mar 29 '22 at 10:14
  • 1
    I strongly recommend you enable warnings with the `-Wall` flag and carefully read them. Many beginner's mistakes, such as this one, are caught by warnings. Here the warning would say something like "unhandled case: []" pointing at the empty list. – chi Mar 29 '22 at 11:32

1 Answers1

4

There is no redundant pattern, there patterns are non-exhaustive: these do not consider the empty list. You thous implement evens and odds with:

sumEvenOdd :: Num a => [a] -> (a, a)
sumEvenOdd xs = (sum (evens xs), sum (odds xs))

evens :: [a] -> [a]
evens [] = []
evens (x:xs) = x : odds xs

odds :: [a] -> [a]
odds [] = []
odds (_:xs) = evens xs

You can use sum :: (Foldable f, Num a) => f a -> a. Using foldl1 (+) will not work for empty lists.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Would `(foldl (+) 0 evens xs, foldl (+) 0 odds xs) ` work as well? Thanks for the quick answer by the way – User0name00 Mar 29 '22 at 23:39
  • @User0name00 It would. But `sum` would be generally preferable, since it is more expressive and can potentially be more efficient. – Wheat Wizard Mar 30 '22 at 12:19