Skip to content

Instantly share code, notes, and snippets.

@orb orb/lesson1.hs
Created Oct 25, 2014

Embed
What would you like to do?
haskell 1
-- exercise 1
toDigitsRev n = if (n <= 0)
then []
else (n `mod` 10) : (toDigitsRev (n `div` 10))
toDigits = reverse . toDigitsRev
-- exercise 2
doubleEveryOther = reverse . doubleHelperOdd . reverse
doubleHelperOdd [] = []
doubleHelperOdd (x:xs) = x : (doubleHelperEven xs)
doubleHelperEven [] = []
doubleHelperEven (x:xs) = (2 * x) : (doubleHelperOdd xs)
-- exercise 3
sumDigitsX [] = 0
sumDigitsX (x:xs) =
let sumFirst = if (x>10)
then (1 + (x `mod` 10))
else (x `mod` 10)
in
sumFirst + (sumDigitsX xs)
sumDigitsY ns = sum (foldl (++) [] (map toDigits ns))
sumDigitsZ ns = sum (concatMap toDigits ns)
sumDigits = sum . (concatMap toDigits)
-- exercise 4
validate digits =
remainder == 0
where digitSum = (sumDigits . doubleEveryOther . toDigits) digits
remainder = digitSum `mod` 10
-- exercise 5
type Peg = String
type Move = (Peg, Peg)
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi 0 a b c = []
--hanoi 1 a b c = [(a,b)]
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
You can’t perform that action at this time.