Created
March 22, 2014 18:16
-
-
Save luca-bernardi/9711786 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- CIS 194: Homework 1 (http://www.seas.upenn.edu/~cis194/hw/01-intro.pdf) | |
-- toDigits 1234 == [1,2,3,4] | |
-- toDigitsRev 1234 == [4,3,2,1] | |
-- toDigits 0 == [] | |
-- toDigits (-17) == [] | |
toDigitsRev :: Integer -> [Integer] | |
toDigitsRev x = if x <= 0 | |
then [] | |
else (x `mod` 10) : toDigitsRev (x `div` 10) | |
-- Alternative declaration using guards | |
toDigitsRev' x | |
| x <= 0 = [] | |
| otherwise = (x `mod` 10) : toDigitsRev' (x `div` 10) | |
toDigits :: Integer -> [Integer] | |
toDigits x = reverse (toDigitsRev x) | |
-- Example: doubleEveryOther [8,7,6,5] == [16,7,12,5] | |
-- Example: doubleEveryOther [1,2,3] == [1,4,3] | |
doubleEveryOther' :: [Integer] -> [Integer] | |
doubleEveryOther' [] = [] | |
doubleEveryOther' [x] = [x] | |
doubleEveryOther' (x:y:xs) = x : (y * 2) : doubleEveryOther' xs | |
doubleEveryOther xs = reverse (doubleEveryOther' (reverse xs)) | |
-- Example: sumDigits [16,7,12,5] = 1 + 6 + 7 + 1 + 2 + 5 = 22 | |
sumDigits :: [Integer] -> Integer | |
sumDigits [] = 0 | |
sumDigits (x:xs) | |
| x < 10 = x + sumDigits xs | |
| otherwise = sumDigits ((toDigits x) ++ xs) | |
-- Example: validate 4012888888881881 = True | |
-- Example: validate 4012888888881882 = False | |
validate :: Integer -> Bool | |
validate cc = ((sumDigits (doubleEveryOther (toDigits cc))) `mod` 10) == 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment