Created
September 20, 2013 13:12
-
-
Save zsol/6637306 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
module Card where | |
import Data.Char | |
produceDigits :: Integer -> [Int] | |
produceDigits n = [(ord i) - 48| i <- (show n)] | |
doubleEveryOther :: [Int] -> [Int] | |
doubleEveryOther l = case (length l) `mod` 2 of | |
0 -> helper0 l | |
1 -> helper1 l | |
helper0 :: [Int] -> [Int] | |
helper0 [] = [] | |
helper0 (x : xs) = 2 * x : helper1 xs | |
helper1 :: [Int] -> [Int] | |
helper1 (x : xs :xss) = x : 2 * xs : helper1 xss | |
helper1 l = l | |
sumDigits :: Int -> Int | |
sumDigits = sum . produceDigits . fromIntegral | |
validate :: Integer -> Bool | |
validate cardNumber = checkSum == last thirdRow | |
where thirdRow = map sumDigits $ doubleEveryOther $ produceDigits cardNumber | |
checkSum = (10 - ) $ (`mod` 10) $ sum $ init thirdRow | |
data Issuer = MasterCard | Visa | |
issuer :: Integer -> Issuer | |
issuer = undefined | |
-- validate 79927398713 == True | |
-- validate 79927398712 == False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I still wanted to add a more compact doubleEveryOther :)
doubleEveryOther :: [Int] -> [Int]
doubleEveryOther [] = []
doubleEveryOther (x:[]) = (x:[])
doubleEveryOther (x:xs:xss) = x : xs * 2 : doubleEveryOther xss