Skip to content

Instantly share code, notes, and snippets.

@zsol
Created September 20, 2013 13:12
Show Gist options
  • Save zsol/6637306 to your computer and use it in GitHub Desktop.
Save zsol/6637306 to your computer and use it in GitHub Desktop.
credit card validation
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
@johannesschirrmeister
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment