summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEdoardo La Greca2025-04-01 16:45:21 +0200
committerEdoardo La Greca2025-04-01 16:47:30 +0200
commit5c0cc518bbc165153c48bb87b9e776760028973a (patch)
tree6486b6e6163a635f5764aca1d8f88dadc78d231e
parent74fad25e20c20f4c9d8541f37ef1abf368626d88 (diff)
add exercises 1 to 4 to first lecture's homework
-rw-r--r--lec01/hw.hs41
1 files changed, 41 insertions, 0 deletions
diff --git a/lec01/hw.hs b/lec01/hw.hs
index 491d74d..8f4197d 100644
--- a/lec01/hw.hs
+++ b/lec01/hw.hs
@@ -1 +1,42 @@
-- homework for lecture 1
+
+-- exercise 1
+
+toDigits :: Integer -> [Integer]
+toDigits n
+ | n > 0 = toDigits (n `div` 10) ++ [n `mod` 10]
+ | otherwise = []
+
+revList :: [Integer] -> [Integer]
+revList [] = []
+revList (x:xs) = revList xs ++ [x]
+
+toDigitsRev :: Integer -> [Integer]
+toDigitsRev n = revList (toDigits n)
+
+-- exercise 2
+
+-- [SIDE NOTE] The exercise specifies that the function below "should double
+-- every other number *beginning from the right*". However, it's unclear
+-- whether this is a requirement (i.e. the function must double digits in
+-- reverse order) or a mere clarification to better understand which numbers
+-- should be doubled and which not. Since the order doesn't matter (and doing
+-- the operation in reverse order would also complicate the solution), I
+-- decided to do it from left to right, the usual order.
+doubleEveryOther :: [Integer] -> [Integer]
+doubleEveryOther [] = []
+doubleEveryOther (x:y:ys) = x*2 : (y : doubleEveryOther ys)
+
+-- exercise 3
+
+-- This function assumes that the list only contains numbers between 0 and 19
+sumDigits :: [Integer] -> Integer
+sumDigits [] = 0
+sumDigits (x:xs)
+ | x >= 10 = (1 + x `mod` 10) + sumDigits xs
+ | otherwise = x + sumDigits xs
+
+-- exercise 4
+
+validate :: Integer -> Bool
+validate n = sumDigits (doubleEveryOther (toDigits n)) `mod` 10 == 0