Last active
August 29, 2015 14:06
-
-
Save Rydgel/25563c8336c23fc9a183 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) | |
-- Part I - Credit Card Validation | |
toDigits :: Integer -> [Integer] | |
toDigits n | |
| n <= 0 = [] | |
| otherwise = toDigits (n `div` 10) ++ [n `mod` 10] | |
toDigitsRev :: Integer -> [Integer] | |
toDigitsRev = reverse . toDigits | |
doubleEveryTwo :: [Integer] -> [Integer] | |
doubleEveryTwo [] = [] | |
doubleEveryTwo (x:[]) = [x] | |
doubleEveryTwo (x:(y:zs)) = [x] ++ [2 * y] ++ doubleEveryTwo zs | |
doubleEveryOther :: [Integer] -> [Integer] | |
doubleEveryOther = reverse . doubleEveryTwo . reverse | |
sumDigits :: [Integer] -> Integer | |
sumDigits = sum . concatMap toDigits | |
validate :: Integer -> Bool | |
validate = (==0) . (`mod` 10) . sumDigits . doubleEveryOther . toDigits | |
-- Part II - Hanoi Tower | |
type Peg = String | |
type Move = (Peg, Peg) | |
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] | |
hanoi 0 _ _ _ = [] | |
hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a | |
main = do putStrLn "Credit card validation" | |
print $ toDigits 1234 | |
print $ toDigitsRev 1234 | |
print $ toDigits 0 | |
print $ toDigits (-17) | |
print $ doubleEveryOther [8,7,6,5] | |
print $ doubleEveryOther [1,2,3] | |
print $ sumDigits [16,7,12,5] | |
print $ validate 4012888888881881 | |
print $ validate 4012888888881882 | |
putStrLn "---------------------" | |
putStrLn "Hanoi tower" | |
print $ hanoi 2 "a" "b" "c" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment