-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHW01.hs
58 lines (43 loc) · 2.24 KB
/
HW01.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
{-# OPTIONS_GHC -Wall #-}
module HW01 where
-- Exercise 1 -----------------------------------------
-- Get the last digit from a number
-- Note : casting (last (show x)) to array to make String from char. -- Ger
lastDigit :: Integer -> Integer
lastDigit x = read [(last (show x))]
-- Drop the last digit from a number
dropLastDigit :: Integer -> Integer
dropLastDigit x = read (replaceEmptyStringByZero (init (show x)))
replaceEmptyStringByZero :: String -> String
replaceEmptyStringByZero x = if (length x) > 0 then x
else "0"
-- Exercise 2 -----------------------------------------
toRevDigits :: Integer -> [Integer]
toRevDigits x = if x > 0 then lastDigit x : toRevDigits (dropLastDigit x)
else []
-- Exercise 3 -----------------------------------------
-- Double every second number in a list starting on the left.
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther [] = []
doubleEveryOther xs = head xs : doubleNow (tail xs)
doubleNow :: [Integer] -> [Integer]
doubleNow [] = []
doubleNow xs = 2 * (head xs) : doubleEveryOther (tail xs)
-- Exercise 4 -----------------------------------------
-- Calculate the sum of all the digits in every Integer.
sumDigits :: [Integer] -> Integer
sumDigits xs = sumLeft (fixLeftmostDigit xs)
-- Splits the starting digit so it can be used to correctly calculate sum
-- if starting value of that digit >= 10
fixLeftmostDigit :: [Integer] -> [Integer]
fixLeftmostDigit xs = if (head xs > 9) then (head xs) - 9 : tail xs
else xs
-- Sums every digit seperately (substracting 9 is the same as adding the digits seperately for values under 20)
sumLeft :: [Integer] -> Integer
sumLeft xs = if (length xs) == 1 then head xs
else if (head (tail xs)) > 9 then sumLeft (head xs + ((head (tail xs)) - 9) : tail (tail xs))
else sumLeft (head xs + head (tail xs) : tail (tail xs))
-- Exercise 5 -----------------------------------------
-- Validate a credit card number using the above functions.
luhn :: Integer -> Bool
luhn x = (lastDigit x) == 10 - lastDigit((sumDigits (tail (doubleEveryOther (toRevDigits x)))))