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
62
63
64
|
import Data.Char
import Data.List
-- Exercise 1
squareDigits :: Int -> Int
squareDigits n = read (concat (map (\c -> if not (c == '-') then show ((digitToInt c)^2) else c : "") (show n))) :: Int
-- Exercise 2
data Stock = Stock String Int
stocklist :: [Stock] -> [Char] -> [(Char,Int)]
stocklist [] _ = []
stocklist _ [] = []
stocklist l m = map (\cat -> (cat, foldr (\(Stock c n) acc -> if cat == head c then acc + n else acc) 0 l)) m
-- Exercise 3
matching :: String -> [(Int, Int)]
matching s = calc s 0 []
where
calc [] _ _ = []
calc s i stack = case head s of
'[' -> calc (tail s) (i + 1) (i : stack)
']' -> (head stack, i) : (calc (tail s) (i + 1) (tail stack))
otherwise -> calc (tail s) (i + 1) stack
-- Exercise 4
data BTree a = Nil | Node a (BTree a) (BTree a)
nodeCount :: BTree a -> Int
nodeCount Nil = 0
nodeCount (Node _ t1 t2) = 1 + nodeCount t1 + nodeCount t2
treeHeight :: BTree a -> Int
treeHeight Nil = 0
treeHeight (Node _ t1 t2) = 1 + max (treeHeight t1) (treeHeight t2)
isPerfectlyBalanced :: BTree a -> Bool
isPerfectlyBalanced t = nodeCount t == (2^treeHeight t) - 1
main :: IO()
main = do
print(squareDigits 9119)
print(squareDigits (-9119))
let stocks = [Stock "ABAR" 200, Stock "CDXE" 500, Stock "BKWR" 250, Stock "BTSQ" 890, Stock "DRTY" 600]
print(stocklist stocks ['A','B']) -- ➝ [('A',200),('B',1140)]
print(stocklist stocks ['C','X']) -- ➝ [('C',500),('X',0)]
print(stocklist stocks ['Y','X']) -- ➝ [('Y',0),('X',0)]
print(stocklist stocks ['C']) -- ➝ [('C', 500)]
print(matching "1234") -- ➝ []
print(matching ",[.[-],]") -- ➝ [(3,5),(1,7)]
print(matching ",+[-.,+]") -- ➝ [(2,7)]
print(matching "[][]") -- ➝ [(0,1),(2,3)]
let t1 = Node 'H' (Node 'a' (Node 'k' Nil Nil)
(Node 'e' Nil Nil))
(Node 's' (Node 'l' Nil Nil)
(Node 'I' Nil Nil))
print(isPerfectlyBalanced t1) -- == True
|