Solutions to the week 1 homework exercises in Brent Yorgey's 2013 offering of cis194.
Created
July 25, 2018 21:48
-
-
Save beeleebow/acc99059be05d52d7668f0a10d35b917 to your computer and use it in GitHub Desktop.
cis194 w01 solution
This file contains 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
module Week01.CreditCardValidator | |
( toDigits | |
, toDigitsRev | |
, doubleEveryOther | |
, sumDigits | |
, validate | |
) where | |
reverseList :: [Integer] -> [Integer] | |
reverseList [] = [] | |
reverseList (x:xs) = reverseList xs ++ [x] | |
toDigits :: Integer -> [Integer] | |
toDigits n = reverseList (toDigitsRev n) | |
toDigitsRev :: Integer -> [Integer] | |
toDigitsRev n | |
| n <= 0 = [] | |
| otherwise = n `mod` 10 : toDigitsRev (n `div` 10) | |
doubleEveryOtherFromLeft :: [Integer] -> [Integer] | |
doubleEveryOtherFromLeft [] = [] | |
doubleEveryOtherFromLeft (x:y:zs) = x : 2*y : doubleEveryOtherFromLeft zs | |
doubleEveryOtherFromLeft (x:[]) = [x] | |
doubleEveryOther :: [Integer] -> [Integer] | |
doubleEveryOther xs = reverseList (doubleEveryOtherFromLeft (reverseList xs)) | |
sumInts :: [Integer] -> Integer | |
sumInts [] = 0 | |
sumInts (x:xs) = x + sumInts xs | |
sumDigits :: [Integer] -> Integer | |
sumDigits [] = 0 | |
sumDigits (x:xs) = sumInts (toDigits x) + (sumDigits xs) | |
validate :: Integer -> Bool | |
validate n = sumDigits (doubleEveryOther (toDigits n)) `mod` 10 == 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment