Homework 4

21-06-16–21-06-29

Exercise 1

fun1 :: [Integer] -> Integer
fun1 []         = 1
fun1 (x:xs) 
  | even x      = (x - 2) * fun1 xs 
  | otherwise   = fun1 xs


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

fun2 :: Integer -> Integer
fun2 1 = 0
fun2 n 
  | even n    = n + fun2 (n `div` 2)
  | otherwise = fun2 (3 * n + 1)
fun2' :: Integer -> Integer 
fun2' = sum . filter even . takeWhile (>1) . iterate helper  

helper :: Integer -> Integer 
helper n
  | even n    = n `div` 2 
  | otherwise = 3 * n + 1  

Exercise 2

The height of a binary tree is the length of the path from the root to the deepest node.

e.g. the height of a tree with a single node is 0.

A binary tree is balanced if the height of its left and right subtrees differed by no more than 1, and its left and right subtrees are also balanced.

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

foldTree :: [a] -> Tree a
foldTree [a] = Node 0 Leaf a Leaf
foldTree list =  

Start by making a helper that simply add to a subtree to an existing tree.

helper :: a -> Tree a -> Tree a 
helper a Leaf = Node 0 Leaf a Leaf 
helper a Node n Leaf b (Tree c) =  Node n () b (Tree c)