haskell - Luhn algorithm implementation -
i'm expecting luhn 5594589764218858 = true
false
-- last digit number lastdigit :: integer -> integer lastdigit 0 = 0 lastdigit n = mod n 10 -- drop last digit number droplastdigit :: integer -> integer droplastdigit n = div n 10 torevdigits :: integer -> [integer] torevdigits n | n <= 0 = [] | otherwise = lastdigit n : torevdigits (droplastdigit n) -- double every second number in list starting on left. doubleeveryother :: [integer] -> [integer] doubleeveryother [] = [] doubleeveryother (x : []) = [x] doubleeveryother (x : y : z) = x : (y * 2) : doubleeveryother z -- calculate sum of digits in every integer. sumdigits :: [integer] -> integer sumdigits [] = 0 sumdigits (x : []) = x sumdigits (x : y) = (lastdigit x) + (droplastdigit x) + sumdigits y -- validate credit card number using above functions. luhn :: integer -> bool luhn n | sumdigits (doubleeveryother (torevdigits n)) `div` 10 == 0 = true | otherwise = false
i know can done easier i'm following haskell introductory. think problem in luhn
function. course mentions problems may occur because torevdigits
reverses number think should work anyways.
the snippet x `div` 10 == 0
not correct check x
divisible ten; should use `mod`
instead. also, equation incorrect:
sumdigits (x : []) = x
(try, e.g. sumdigits [10]
.) can fixed, deleting simpler , still correct.
Comments
Post a Comment