-
Notifications
You must be signed in to change notification settings - Fork 0
/
hw1.hs
40 lines (32 loc) · 1.33 KB
/
hw1.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
import Data.Char
-- -- toDigits convert an number to array of its digits
toDigits :: Integer -> [Integer]
toDigits = reverse . toDigitsRev
-- toDigitsRev reverse return the digits in reverse as array
toDigitsRev :: Integer -> [Integer]
toDigitsRev n
| n <= 0 = []
| otherwise = (n `mod` 10) : toDigitsRev (n `quot` 10)
-- doubleNext double the every other item in list
doubleNext :: Bool -> [Integer] -> [Integer]
doubleNext _ [] = []
doubleNext True (x:xs) = x + x : doubleNext False xs
doubleNext False (x:xs) = x : doubleNext True xs
-- doubleEveryOther double every other number beginning from the right,
-- that is, the second-to-last, fourth-to-last, etc ..
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther = reverse. (doubleNext False) . reverse
-- sumDigits sum all the digits in Integer list
sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x:xs) = (sum . toDigits) x + sumDigits xs
-- validate check whether the given credit card is valid or not
validate :: Integer -> Bool
validate n = (sumDigits . doubleEveryOther . toDigits) n `mod` 10 == 0
-- Exercise 5 : tower of hanoi
type Peg = String
type Move = (Peg, Peg)
-- hanoi computes move for tower of hanio puzzle
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi 1 a b _ = [(a, b)]
hanoi n a b c = hanoi (n - 1) a c b ++ [(a, b)] ++ hanoi (n - 1) c b a