Curious
Curious

Reputation: 921

haskell non-exhaustive patterns missing

I'm getting following error for the below, I assume all the recursive cases, What is missing ?

Prelude> product [] =1
Prelude> product (x:xs) =x * product xs
Prelude> product [1,2,3]
*** Exception: <interactive>:48:1-30: Non-exhaustive patterns in function product

Upvotes: 3

Views: 453

Answers (2)

chi
chi

Reputation: 116139

I strongly recommend to turn on warnings with -Wall. Doing so, here, would also hint at the fact that each definition is considered separately.

> :set -Wall
> product [] = 1

<interactive>:2:1: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for ‘product’: Patterns not matched: (_:_)
> product (x:xs) = x * product xs

<interactive>:3:1: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for ‘product’: Patterns not matched: []

Indeed, note how the last warning complaints about [] not being matched, showing that the first definition product [] was ignored.

Upvotes: 2

Rein Henrichs
Rein Henrichs

Reputation: 15605

GHCi processes each line separately, so you have defined a function

product [] = 1

and then shadowed product by defining a new function

product (x:xs) = x * product xs

To fix this, you can use :{ and :} for a multiline block:

:{
product [] = 1
product (x:xs) = x * product xs
:}

or, and this is what I would recommend, put your function definitions in a file and load them in GHCi.

Upvotes: 8

Related Questions