Credit card number validation

master
mandlm 2016-09-22 23:50:31 +02:00
parent ab98b7cf3d
commit 566bdfc66c
3 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,32 @@
lastDigit :: Integer -> Integer
lastDigit n = n `mod` 10
dropLastDigit :: Integer -> Integer
dropLastDigit n = n `div` 10
toDigits :: Integer -> [Integer]
toDigits n
| n <= 0 = []
| otherwise = toDigits(dropLastDigit(n)) ++ [lastDigit(n)]
doubleEveryOtherLeft :: [Integer] -> [Integer]
doubleEveryOtherLeft [] = []
doubleEveryOtherLeft (x:[]) = [x]
doubleEveryOtherLeft (x:y:zs) = x : (y * 2) : doubleEveryOtherLeft(zs)
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther x = reverse(doubleEveryOtherLeft(reverse(x)))
crossSum :: Integer -> Integer
crossSum x
| x < 10 = x
| otherwise = lastDigit(x) + crossSum(dropLastDigit(x))
sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x:xs) = crossSum(x) + sumDigits(xs)
validate :: Integer -> Bool
validate x = lastDigit(sumDigits(doubleEveryOther(toDigits(x)))) == 0

View File

@ -0,0 +1,3 @@
isEven :: Integer -> Bool
isEven n = n `mod` 2 == 0

View File

@ -0,0 +1,10 @@
sumFun :: Integer -> Integer
sumFun 0 = 0
sumFun n
| n < 0 = 0
| otherwise = sumFun(n - 1) + n
sumList :: Integer -> [Integer]
sumList 0 = []
sumList n = sumFun(n) : sumList(n - 1)