+{-# OPTIONS_GHC -Wall #-}
+
module Hw4 where
-- wholemeal programming
fun2' n = sum $ filter even $ takeWhile (/= 1) $ iterate gen n
where gen x | even x = x `div` 2
| otherwise = 3 * x + 1
+
+-- exercise 2
+-- folding with trees
+
+data Tree a = Leaf
+ | Node Integer (Tree a) a (Tree a)
+ deriving (Show, Eq)
+
+-- generate balanced binary tree using foldr
+height :: Tree a -> Integer
+height Leaf = 0
+height (Node h _ _ _) = h
+
+balanced :: Tree a -> Bool
+balanced Leaf = True
+balanced (Node _ lt _ rt) = abs (height lt - height rt) <= 1 &&
+ balanced lt && balanced rt
+
+insert :: a -> Tree a -> Tree a
+insert x Leaf = Node 0 Leaf x Leaf
+insert x (Node h lt v rt) | h1 < h2 = Node h (insert x lt) v rt
+ | h1 > h2 = Node h lt v (insert x rt)
+ | otherwise = Node (newh + 1) lt v (insert x rt)
+ where h1 = height lt
+ h2 = height rt
+ newh = height (insert x rt)
+
+foldTree :: [a] -> Tree a
+foldTree = foldr f Leaf
+ where f x acc = insert x acc
+
+