-
Notifications
You must be signed in to change notification settings - Fork 0
/
HW01.hs
61 lines (47 loc) · 1.84 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
59
60
61
{-# OPTIONS_GHC -Wall #-}
module HW01 where
-- Exercise 1 -----------------------------------------
-- Get the last digit from a number
lastDigit :: Integer -> Integer
lastDigit = (`mod` 10)
-- same as lastDigit x = x `mod` 10
-- Drop the last digit from a number
dropLastDigit :: Integer -> Integer
dropLastDigit = (`div` 10)
-- Exercise 2 -----------------------------------------
toRevDigits :: Integer -> [Integer]
toRevDigits x
| x < 1 = []
| otherwise = lastDigit x : (toRevDigits (dropLastDigit x))
-- Exercise 3 -----------------------------------------
-- Double every second number in a list starting on the left.
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther (x:(y:zs)) = x : (y*2) : (doubleEveryOther zs)
doubleEveryOther xs = xs
-- Exercise 4 -----------------------------------------
-- Calculate the sum of all the digits in every Integer.
sumDigits :: [Integer] -> Integer
sumDigits = sum . map (sum . toRevDigits)
-- Exercise 5 -----------------------------------------
-- Validate a credit card number using the above functions.
luhn :: Integer -> Bool
luhn =
(f x) `mod` 10 == 0
where f = sumDigits . doubleEveryOther . toRevDigits
-- could write this like this (but it would be hard to read):
-- luhn = (== 0) . (`mod` 10) . sumDigits . doubleEveryOther . toRevDigits
-- Exercise 6 -----------------------------------------
-- Towers of Hanoi for three pegs
type Peg = String
type Move = (Peg, Peg)
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi 0 _ _ _ = [] -- no moves possible with an empty set
hanoi n src dest tmp =
hanoi (n-1) src tmp dest ++ [(src, dest)] ++ hanoi (n-1) tmp dest src
{-
1. move n − 1 discs from a to b using c as temporary storage
2. move the top disc
from a to c
3. move n − 1 discs from b to c using a as temporary storage.
-}
-- hanoi 2 "a" "b" "c" == [("a","c"), ("a","b"), ("c","b")]