1

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

Will Ness
  • 70,110
  • 9
  • 98
  • 181
Barburka
  • 407
  • 1
  • 7
  • 15
  • 3
    Possible duplicate of [Exception: Non-exhaustive patterns in function](https://stackoverflow.com/questions/17983936/exception-non-exhaustive-patterns-in-function) / [Non exhaustive pattern in function noThirds](https://stackoverflow.com/questions/23178455/non-exhaustive-pattern-in-function-nothirds) – TrebledJ Jun 14 '19 at 04:14
  • There is no "map" word in these posts. – Barburka Jun 14 '19 at 04:28
  • 2
    Indeed there is not. But the dupes should be sufficient in fixing the "Non-exhaustive patterns" exception, the crux of your question. Regarding map/recursion... `map` already works over a list, so either use recursion or `map`. I don't see how you can use both effectively together. – TrebledJ Jun 14 '19 at 04:31
  • I don't want to use it together. I have a homework where I have to solve the problem in three different ways (map, recursion and list comprehensions). My post is clear instead of those. – Barburka Jun 14 '19 at 04:35
  • 2
    Ah... "_I has to use recursion [...] and map function_" ← I thought "_and_" here meant you would like to use both together. Running the given code by itself also doesn't cause any errors, you should include how you're calling `mult` (e.g. `mult [1, 2, 3]`). Overall, your question could be clearer. I personally find the "_Non exhaustive pattern in function noThirds_" question clear enough to solve your issue with non-exhaustive patterns. But Will's answer below is good too. – TrebledJ Jun 14 '19 at 04:44

2 Answers2

6

[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.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
-2

Solution:

fun x = 3 * x + 1
mult :: [Int] -> [Int]
mult (x:xs) = map fun (x:xs)
Barburka
  • 407
  • 1
  • 7
  • 15