Search code examples
listhaskellrecursionghci

Patterns not matched: Haskell


I wrote a function that takes a list as an input and outputs the sum of its elements, but I get the following error: "Pattern match(es) are non-exhaustive In an equation for ‘addfunc’: Patterns not matched: []"

Here is my code:

addfunc :: [Int] -> Int
addfunc(x:xs) = x + addfunc xs

Solution

  • When pattern matching, you have to list out all possible cases, so that your program knows what to do for every possible input. Here, the possible input is all lists of integers, which also includes an empty list (a list of zero integers). Your function knows what to do when the input has a first element and other elements; but if it should receive an empty list (which cannot be decomposed into the first element and the other elements), it would not know what to do.

    To correct it, simply provide the matching rules for the missing case(s), e.g.

    addfunc [] = 0