0
votes

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?

2
did you mean for that to just apply to singleton lists? Or did you mean it to apply to all lists: ie. luhn xs = myMap (*2) (+0) xs Which in turn can be simplified as luhn = myMap (*2) (+0) (and I would prefer to write id instead of (+0), but that makes no difference). - Robin Zigmond

2 Answers

1
votes

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.

0
votes

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!"