1
+ module Ch8 where
2
+
3
+ -- 1. In a similar manner to the function add, define a recursive multiplication function
4
+ -- mult :: Nat -> Nat -> Nat for the recursive type of natural numbers:
5
+ data Nat = Zero | Succ Nat deriving (Show )
6
+
7
+ add :: Nat -> Nat -> Nat
8
+ add Zero n = n
9
+ add (Succ m) n = Succ (m `add` n)
10
+
11
+ mult :: Nat -> Nat -> Nat
12
+ mult _ Zero = Zero
13
+ mult m (Succ n) = m `add` (m `mult` n)
14
+
15
+ -- 2. Using the library function compare, redefine the function occurs for search trees.
16
+ -- Why is this new definition more efficient than the original version?
17
+ data Tree a = Leaf a | Node (Tree a ) a (Tree a )
18
+
19
+ occurs :: Ord a => a -> Tree a -> Bool
20
+ occurs x (Leaf y) = x == y
21
+ occurs x (Node l y r) | c == EQ = True
22
+ | c == LT = occurs x l
23
+ | otherwise = occurs x r
24
+ where c = compare x y
25
+
26
+ -- Is more efficient because it only goes through one path in the entire tree instead of
27
+ -- checking all branches.
28
+
29
+ -- 3. Define a function balanced :: Tree a -> Bool that decides if a binary tree is
30
+ -- balanced or not.
31
+ data Tree2 a = Leaf2 a | Node2 (Tree2 a ) (Tree2 a )
32
+
33
+ leaves :: Tree2 a -> Int
34
+ leaves (Leaf2 _) = 1
35
+ leaves (Node2 l r) = leaves l + leaves r
36
+
37
+ balanced :: Tree2 a -> Bool
38
+ balanced (Leaf2 _) = True
39
+ balanced (Node2 l r) = leaves l == leaves r
40
+ || leaves l == leaves r - 1
41
+ || leaves l == leaves r + 1
42
+
43
+ -- 4. Define a function balance :: [a] -> Tree a that converts a non-empty list into a
44
+ -- balanced tree.
45
+ halve :: [a ] -> ([a ], [a ])
46
+ halve xs = splitAt (length xs `div` 2 ) xs
47
+
48
+ balance :: [a ] -> Tree2 a
49
+ balance [x] = Leaf2 x
50
+ balance xs = Node2 (balance h1) (balance h2)
51
+ where (h1, h2) = halve xs
52
+
53
+ -- 5. Given the type declaration:
54
+ data Expr = Val Int | Add Expr Expr
55
+ -- define a higher-order function
56
+ folde :: (Int -> a ) -> (a -> a -> a ) -> Expr -> a
57
+
58
+ -- such that folde fg replaces Val by f and Add by g.
59
+ folde f g (Val n) = f n
60
+ folde f g (Add a b) = g (folde f g a) (folde f g b)
61
+
62
+ -- 6. Using folde, define a function eval that evaluates an Expr to an integer value, and
63
+ -- size that calculates the number of values in an expression.
64
+ eval :: Expr -> Int
65
+ eval = folde id (+)
66
+
67
+ size :: Expr -> Int
68
+ size = folde (const 1 ) (+)
69
+
70
+ -- 7. Complete the following instance declarations:
71
+ instance Eq a => Eq (Maybe a ) where
72
+ Nothing == Nothing = True
73
+ (Just a) == (Just b) = a == b
74
+ _ == _ = False
75
+
76
+ instance Eq a => Eq [a ] where
77
+ [] == [] = True
78
+ [a] == [b] = a == b
79
+ (a: as) == (b: bs) = a == b && as == bs
80
+ _ == _ = False
0 commit comments