Credit card number validation
This commit is contained in:
parent
ab98b7cf3d
commit
566bdfc66c
32
Lecture 01/CreditCardValidation/CreditCard.hs
Normal file
32
Lecture 01/CreditCardValidation/CreditCard.hs
Normal 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
|
3
Lecture 01/scratch/isEven.hs
Normal file
3
Lecture 01/scratch/isEven.hs
Normal file
@ -0,0 +1,3 @@
|
||||
isEven :: Integer -> Bool
|
||||
isEven n = n `mod` 2 == 0
|
||||
|
10
Lecture 01/scratch/sumFun.hs
Normal file
10
Lecture 01/scratch/sumFun.hs
Normal 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)
|
||||
|
Reference in New Issue
Block a user