Skip to content

Instantly share code, notes, and snippets.

@beeleebow
Created July 25, 2018 21:48
Show Gist options
  • Save beeleebow/acc99059be05d52d7668f0a10d35b917 to your computer and use it in GitHub Desktop.
Save beeleebow/acc99059be05d52d7668f0a10d35b917 to your computer and use it in GitHub Desktop.
cis194 w01 solution

What is this?

Solutions to the week 1 homework exercises in Brent Yorgey's 2013 offering of cis194.

Links

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