From a32f460a998b2d4b24ac619292c9c5f599e28c7d Mon Sep 17 00:00:00 2001 From: Tristan Cacqueray Date: May 09 2019 11:42:32 +0000 Subject: Add tdecacqu answers for the first week Depends-On: https://pagure.io/cis194/pull-request/1 --- diff --git a/assignments/tdecacqu/01.lhs b/assignments/tdecacqu/01.lhs new file mode 100644 index 0000000..29b995e --- /dev/null +++ b/assignments/tdecacqu/01.lhs @@ -0,0 +1,79 @@ +Syntax note: + +* otherwise == True +* 5 `mod` 2 == mod 5 2 + +Useful function + +* fromIntegral: convert Int to other numeric types +* round, floor, ceiling: convert numeric types to Int + +Enable unicode symbols: + +> {-# LANGUAGE UnicodeSyntax #-} +> -- https://stackoverflow.com/questions/24441661/haskell-mode-not-working-for-my-project-cant-find-module +> import Prelude.Unicode + +Add a main + +> main :: IO () +> main = print "Hello" + +** Exercise 1 + +First the toDigitsRev as it's more natural with cons: + +> toDigitsRev ∷ Integer → [Integer] +> toDigitsRev x +> | x ≤ 0 = [] +> | x ≥ 10 = mod x 10 : toDigitsRev (div x 10) +> | otherwise = [x] + +Then a procedure to reverse a list: + +> listRev ∷ [a] → [a] +> listRev (x:xs) = listRev xs ++ [x] +> listRev [] = [] + + +> toDigits ∷ Integer → [Integer] +> toDigits x = listRev (toDigitsRev x) + +** Exercise 2 + +The exercise requires the list to be processed from right to left. +This implementation uses a Do function that works on the reversed list + +> doubleEveryOtherDo ∷ [Integer] → [Integer] +> doubleEveryOtherDo (x:y:xs) = x : y ⋅ 2 : doubleEveryOtherDo xs +> doubleEveryOtherDo (x:[]) = [x] +> doubleEveryOtherDo [] = [] + +> doubleEveryOther ∷ [Integer] -> [Integer] +> doubleEveryOther x = reverse (doubleEveryOtherDo (reverse x)) + +** Exercise 3 + +> sumDigits ∷ [Integer] → Integer +> sumDigits (x:xs) = sum (toDigits x) + sumDigits xs +> sumDigits [] = 0 + +** Exercise 4 + +> validate ∷ Integer → Bool +> validate x = rem (sumDigits (doubleEveryOther (toDigits x))) 10 ≡ 0 + +** Exercise 5 + +> type Peg = String +> type Move = (Peg, Peg) +> hanoi ∷ Integer → Peg → Peg -> Peg → [Move] +> hanoi count source dest spare +> | count ≡ 0 = [] +> | otherwise = hanoi (count - 1) source spare dest ++ +> [(source, dest)] ++ +> hanoi (count - 1) spare dest source + +** Exercise 6 + +-- TODO