summaryrefslogtreecommitdiff
path: root/lec04/hw.hs
blob: 923ec0145521eb1ca2d5c610aedd259c0aff6e55 (plain)
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
-- Exercise 1

fun1 :: [Integer] -> Integer
fun1 = product . map (\n -> n-2) . filter even

-- not tested
fun2 :: Integer -> Integer
fun2 = until (== 1) fun2 . last . takeWhile odd . iterate (\n -> 3*n + 1) . sum . takeWhile even . iterate (`div` 2)

-- Exercise 2

data Tree a = Leaf
    | Node Integer (Tree a) a (Tree a)
    deriving (Show, Eq)

-- Note: I hope I was allowed to make new functions and wasn't supposed to put
-- all the code in `foldTree`, although the exercise didn't say anything in this
-- regard.

treeHeight :: Tree a -> Int
treeHeight Leaf = 0
treeHeight (Node _ Leaf _ Leaf) = 0
treeHeight (Node _ tl _ tr) = 1 + max (treeHeight tl) (treeHeight tr)

treeInsertBalanced :: Tree a -> a -> Tree a
treeInsertBalanced Leaf a                   = Node 0 Leaf a Leaf
treeInsertBalanced t@(Node _ Leaf e Leaf) a = Node 1 (Node 0 Leaf a Leaf) e Leaf
treeInsertBalanced t@(Node _ tl e Leaf) a   = Node 1 tl e (Node 0 Leaf a Leaf)
treeInsertBalanced t@(Node h tl@(Node hl _ _ _) e tr@(Node hr _ _ _)) a
    | hl <= hr  = Node (toInteger newh1) newtl e tr
    | otherwise = Node (toInteger newh1) tl e newtr
    where
        newtl = treeInsertBalanced tl a
        newtr = treeInsertBalanced tr a
        newh1 = max (treeHeight newtl) (treeHeight tr) + 1
        newh2 = max (treeHeight tl) (treeHeight newtr) + 1

foldTree :: [a] -> Tree a
foldTree = foldr (flip treeInsertBalanced) Leaf

-- Exercise 3

xor :: [Bool] -> Bool
xor = odd . foldl (\s x -> if x then s+1 else s) 0

map' :: (a -> b) -> [a] -> [b]
map' f = foldr (\x s -> f x : s) []

myFoldl :: (a -> b -> a) -> a -> [b] -> a
myFoldl f base xs = foldr (flip f) base (reverse xs)