Homework 1

21-06-12–21-06-16

Exercise 1

toDigits :: Integer -> [Integer]
toDigits n 
   | n <= 0 = []
   | otherwise = toDigits (div n 10) ++ [mod n 10]

toDigitsRev :: Integer -> [Integer]
toDigitsRev n = reverse (toDigits n)

Exercise 2

doubleHelper :: [Integer] -> [Integer]
doubleHelper [x] = [x] 
doubleHelper [x,y] = [x, 2*y]
doubleHelper (x:(y:ys)) = [x, 2*y] ++ doubleHelper ys 
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther list = reverse (doubleHelper (reverse list))

Exercise 3

sumDigits :: [Integer] -> Integer 
sumDigits list = sum (map (\n -> sum (toDigits n)) list)

Exercise 4

validate :: Integer -> Bool 
validate n = rem (sumDigits (doubleEveryOther (toDigits n))) 10 == 0

Exercise 5

Given the number of dics and the names for the three pegs, hanoi should return a list of moves to be performed to move the stack of discs from the first peg to the second.

type Peg = String 
type Move = (Peg, Peg) 
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] 
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)