Last active
August 29, 2015 14:18
-
-
Save adolfopa/092063808c1302df4413 to your computer and use it in GitHub Desktop.
Solution to CIS 194 intro to functional programming (HW1)
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.cis.upenn.edu/~cis194/hw/01-intro.pdf) | |
-- Exercise 1 | |
lastDigit :: Integer -> Integer | |
lastDigit n = n `mod` 10 | |
dropLastDigit :: Integer -> Integer | |
dropLastDigit n = n `div` 10 | |
-- Exercise 2 | |
toRevDigits :: Integer -> [Integer] | |
toRevDigits n | |
| n > 0 = lastDigit n : (toRevDigits $ dropLastDigit n) | |
| otherwise = [] | |
-- Exercise 3 | |
doubleEveryOther :: [Integer] -> [Integer] | |
doubleEveryOther xs = map dbl $ zip [1..] xs | |
where dbl (i, n) = if even i then 2 * n else n | |
-- Exercise 4 | |
sumDigits :: [Integer] -> Integer | |
sumDigits xs = sum $ map (sum . toRevDigits) xs | |
-- Exercise 5 | |
luhn :: Integer -> Bool | |
luhn n = x `mod` 10 == 0 | |
where x = sumDigits $ doubleEveryOther $ toRevDigits n | |
-- Exercise 6 | |
type Peg = String | |
type Move = (Peg, Peg) | |
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] | |
hanoi 0 a b c = [] | |
hanoi n a b c = | |
hanoi (n - 1) a c b ++ [(a, b)] ++ hanoi (n - 1) c b a |
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.cis.upenn.edu/~cis194/hw/01-intro.pdf) *) | |
infixr 0 $ | |
fun f $ g = f g | |
fun sum xs = foldl (op+) 0 xs | |
(* Exercise 1 *) | |
fun lastDigit n = n mod 10 | |
fun dropLastDigit n = n div 10 | |
(* Exercise 2 *) | |
fun toRevDigits n = | |
if n > 0 then lastDigit n :: (toRevDigits $ dropLastDigit n) else [] | |
(* Exercise 3 *) | |
fun doubleEveryOther xs = | |
let | |
fun loop [] ys _ = ys | |
| loop (x::xs) ys n = | |
let | |
val y = if n mod 2 = 0 then 2 * x else x | |
in | |
loop xs (y::ys) (n + 1) | |
end | |
in | |
loop xs [] 1 | |
end | |
(* Exercise 4 *) | |
fun sumDigits xs = sum $ map (sum o toRevDigits) xs | |
(* Exercise 5 *) | |
fun luhn n = | |
let | |
val x = sumDigits $ doubleEveryOther $ toRevDigits n | |
in | |
x mod 10 = 0 | |
end | |
(* Exercise 6 *) | |
fun hanoi 0 a b c = [] | |
| hanoi n a b c = | |
hanoi (n - 1) a c b @ [(a, b)] @ hanoi (n - 1) c b a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment