Skip to content

Instantly share code, notes, and snippets.

@orb
Created October 25, 2014 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orb/6faa87181f395e932065 to your computer and use it in GitHub Desktop.
Save orb/6faa87181f395e932065 to your computer and use it in GitHub Desktop.
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