From a8216d87e02525097c3f52161de48b9af48f64eb Mon Sep 17 00:00:00 2001 From: Thomas Cutts <tomcutts@Thomass-MacBook-Pro.local> Date: Tue, 22 Jun 2021 16:02:53 +0100 Subject: [PATCH] Updated readme and added the haskell source code. --- README.md | 7 ++++++- homework1.hs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 homework1.hs diff --git a/README.md b/README.md index 435a32f..ada9e4e 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,8 @@ # Credit Card Validator -Haskell program to validate credit card numbers. \ No newline at end of file +This is an exercise from https://www.cis.upenn.edu/~cis194/spring13/hw/01-intro.pdf. + +I have written a rudimentary checksum formula which could be used to validate credit card numbers. + +To compile: ghc -o egOutputFile homework1.hs +To run: ./egOutputFile diff --git a/homework1.hs b/homework1.hs new file mode 100644 index 0000000..1308c0c --- /dev/null +++ b/homework1.hs @@ -0,0 +1,52 @@ +-- ****EX1**** + +--toDigits 1234 returns [1,2,3,4] +toDigits :: Int -> [Int] +toDigits 0 = [] +toDigits n + | n >=0 = toDigits(n `div` 10) ++ [n `mod` 10] + | otherwise = [] + +--toDigitsRev 1234 returns [4,3,2,1] +toDigitsRev :: Int -> [Int] +toDigitsRev 0 = [] +toDigitsRev n + | n >= 0 = n `mod` 10 : toDigitsRev(n `div` 10) + | otherwise = [] + +-- ****EX2**** + +--doubles every other no. beginning from the rhs of list +doubleEveryOther :: [Int] -> [Int] +doubleEveryOther [] = [] +doubleEveryOther (x:y:z) + | (length (x:y:z)) `mod` 2 /= 0 = x : y*2 : doubleEveryOther z + | otherwise = x*2 : y : doubleEveryOther z + +-- ****EX3**** + +-- calculates the sum of all digits +-- e.g [16,7,12,5] = 1+6+7+1+2+5==22 +sumDigits :: [Int] -> Int +sumDigits [] = 0 +sumDigits (x:xs) + | x < 10 = x + sumDigits xs + | otherwise = (x `mod` 10) + (x `div` 10) + sumDigits xs + + +-- ****EX4**** +--function confirms if the number is a valid credit card number +--number is valid if remainder when div by 10 is 0 +validate :: Int -> Bool +validate n + | (sumDigits (doubleEveryOther (toDigits n))) `mod` 10 == 0 = True + | otherwise = False + +-- main function +main = do + putStrLn("Enter your credit card number") + a <- (readLn) + let b = validate a + if (b == True) + then putStrLn("Valid") + else putStrLn("Invalid") -- GitLab