2

I have two code snippets that throw the same error:

Prelude> sum' [] = 0
Prelude> sum' (x:xs) = x + sum' xs
Prelude> sum' [1,2,3,4,5]
*** Exception: <interactive>:142:1-25: Non-exhaustive patterns in function sum'

and the following as well:

Prelude> prod [] = 1
Prelude> prod (x:xs) = x * (prod xs)
Prelude> prod [1,2,3,4,5]
*** Exception: <interactive>:139:1-27: Non-exhaustive patterns in function prod

I must be missing a pattern, but what is it? Also, how do I such errors? How should I think when defining a function using pattern matching? (I'm asking for a methodolgy/technique)

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
devio
  • 1,147
  • 5
  • 15
  • 41

1 Answers1

5

To create a function with pattern matching, or using multi line in the command line of ghci you should use {} and separate with ; in your case:

Prelude> let { sum' [] = 0 ; sum' (x:xs) = x + sum' xs }
Prelude> sum' [1,2,3,4,5]
=> 15

otherwise you will be binding only one equation (in this case the last one) to the function name sum' and that's why you get a pattern matching failure

developer_hatch
  • 15,898
  • 3
  • 42
  • 75