haskellpattern-matchingnon-exhaustive-patterns

How to fix "Non-exhaustive patterns in function"


I want pass a list as parameter to a function which multiply every element of this list by 3. I has to use recursion (I know how to do it) and map function (there is a problem).

I'm trying passing a list as a parameter as I've seen in other posts but it isn't working.

fun x = 3 * x + 1
mult :: [Int] -> [Int]
mult [a] = map fun [a]

Code I tried shows: Exception: x: Non-exhaustive patterns in function mult


Solution

  • [a] is a singleton list -- a list containing only one element, a.

    As such map f [a] == [f a] and your definition is equivalent to

    mult :: [Int] -> [Int]
    mult [a] = [fun a]
    

    [a] is equivalent to (a : []) both as an expression (something that appears to the right of =) or a pattern (to the left of =).

    (a : []) is a pattern that expresses that tail (a : []) == []. So any list with non-null tail will fail to match that pattern. Any empty list will fail to match it as well.

    These are the cases that your code does not handle. Hence the "non-exhaustive pattern handling" error.

    The exhaustive pair of list-matching patterns are [] and (a : as). One is for empty lists, and the other for non-empty lists with the head element a and tail as.