From 7bc00f7608480e0920e360eb2f3b69296282561d Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan Date: Sat, 20 Dec 2014 12:35:02 +0530 Subject: [PATCH] exercise #2 of hw4. One possible solution --- hw4/hw4.hs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) 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 + + -- 2.37.2