From: Ramakrishnan Muthukrishnan Date: Sat, 20 Dec 2014 07:05:02 +0000 (+0530) Subject: exercise #2 of hw4. One possible solution X-Git-Url: https://git.rkrishnan.org/components/com_hotproperty/%22doc.html/frontends/install.html?a=commitdiff_plain;h=7bc00f7608480e0920e360eb2f3b69296282561d;p=yorgey.git exercise #2 of hw4. One possible solution --- diff --git a/hw4/hw4.hs b/hw4/hw4.hs index efeb3f9..780ee46 100644 --- a/hw4/hw4.hs +++ b/hw4/hw4.hs @@ -1,3 +1,5 @@ +{-# OPTIONS_GHC -Wall #-} + module Hw4 where -- wholemeal programming @@ -35,3 +37,35 @@ fun2' :: Integer -> Integer 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 + +