Sunday, November 23, 2014

Validating credit card numbers in Haskell

This Haskell code can validate a credit card number:

import Data.Char
toDigits :: Integer -> [Integer]
toDigits n = map (\ x -> toInteger (digitToInt x)) (show n)
toDigitsRev :: Integer -> [Integer]
toDigitsRev n = reverse (toDigits n)
doubleSecond :: [Integer] -> [Integer]
doubleSecond [] = []
doubleSecond [a] = a : []
doubleSecond (b : c : xs) = b : 2 * c : doubleSecond xs
sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x : xs) = sum (toDigits x) + sumDigits xs
isValid :: Integer -> Bool
isValid n = mod (sumDigits (doubleSecond (toDigitsRev n))) 10 == 0

No comments:

Post a Comment