From 566bdfc66ce8a4036e981a32c3af59108e75b725 Mon Sep 17 00:00:00 2001 From: Michael Mandl Date: Thu, 22 Sep 2016 23:50:31 +0200 Subject: [PATCH] Credit card number validation --- Lecture 01/CreditCardValidation/CreditCard.hs | 32 +++++++++++++++++++ Lecture 01/scratch/isEven.hs | 3 ++ Lecture 01/scratch/sumFun.hs | 10 ++++++ 3 files changed, 45 insertions(+) create mode 100644 Lecture 01/CreditCardValidation/CreditCard.hs create mode 100644 Lecture 01/scratch/isEven.hs create mode 100644 Lecture 01/scratch/sumFun.hs diff --git a/Lecture 01/CreditCardValidation/CreditCard.hs b/Lecture 01/CreditCardValidation/CreditCard.hs new file mode 100644 index 0000000..cb399ad --- /dev/null +++ b/Lecture 01/CreditCardValidation/CreditCard.hs @@ -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 diff --git a/Lecture 01/scratch/isEven.hs b/Lecture 01/scratch/isEven.hs new file mode 100644 index 0000000..9b84a8e --- /dev/null +++ b/Lecture 01/scratch/isEven.hs @@ -0,0 +1,3 @@ +isEven :: Integer -> Bool +isEven n = n `mod` 2 == 0 + diff --git a/Lecture 01/scratch/sumFun.hs b/Lecture 01/scratch/sumFun.hs new file mode 100644 index 0000000..5ad1033 --- /dev/null +++ b/Lecture 01/scratch/sumFun.hs @@ -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) +