Otavio Bonder
Otavio Bonder

Reputation: 1999

Haskell: Non-exhaustive patterns in function. No idea why

I'm learning Haskell and I'm trying to implement the luhn algorithm.

I've created a helper function:

myMap :: (a -> b) -> (a -> b) -> [a] -> [b]
myMap p q [] = []
myMap p q [x] = [p x]
myMap p q (x : y : xs) = p x : q y : myMap p q xs

This function works fine. If I try to run it as myMap (*2) (+0) [1,2,3,4] it returns [2,2,6,4] which is the expected result.

Than I'm trying to implement the luhn algorithm:

luhn :: [Int] -> [Int]
luhn [x] = myMap (*2) (+0) [x]

This is part of the algorithm, I'll change it to return a Bool, but I'm trying to run as this is and it gives me:

*** Exception: main.hs:92:1-30: Non-exhaustive patterns in function luhn

Why is this happening?

Upvotes: 0

Views: 237

Answers (2)

Otavio Bonder
Otavio Bonder

Reputation: 1999

Thanks everybody, really dumb mistake.

luhn :: [Int] -> [Int]
luhn x = myMap (*2) (+0) x

This was the correct form to implement the function. I don't know why I put luhn [x] = myMap (*2) (+0) [x].

This way it's working now.

Upvotes: 1

ForceBru
ForceBru

Reputation: 44828

What would luhn [] be, for example?

Your function is currently defined for a list of one element. What about other lists?

It can be:

luhn [x] = your code
luhn whatever_else = error "That's an error!"

Upvotes: 0

Related Questions