diff options
Diffstat (limited to 'lec04/hw.hs')
-rw-r--r-- | lec04/hw.hs | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/lec04/hw.hs b/lec04/hw.hs index 1fbdd48..bb5a026 100644 --- a/lec04/hw.hs +++ b/lec04/hw.hs @@ -6,3 +6,34 @@ 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 |