-
-
Save bmabey/b4a1494381fd06353685 to your computer and use it in GitHub Desktop.
Credit Card Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
toDigits :: Integer -> [Integer] | |
toDigits 0 = [] | |
toDigits x = toDigits (div x 10) ++ [(mod x 10)] | |
toDigitsRev :: Integer -> [Integer] | |
toDigitsRev 0 = [] | |
toDigitsRev x = (mod x 10) : toDigitsRev (div x 10) | |
doubleEveryOther :: [Integer] -> [Integer] | |
doubleEveryOther = (reverse . (zipWith ($) (cycle [id, (*2)])) . reverse) | |
sumDigits :: [Integer] -> Integer | |
sumDigits xs = sum (concatMap toDigits xs) | |
validate :: Integer -> Bool | |
validate x = (mod ((sumDigits . doubleEveryOther . toDigits) x) 10) == 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is one way to avoid double-reverse; due to the right-associative nature of foldr, the initial argument will pair with the rightmost element of the list. We can pair each argument with an extra value (isomorphic to Boolean, if you don't want to create a new type for it) to keep track of whether we should double or not. At the end of the recursion, simply discard the parity value.
You can write it a bit more succinctly, but I prefer clarity over succinctness when they conflict.