1 {-# OPTIONS_GHC -Wall #-}
5 -- wholemeal programming
8 1. fun1 :: [Integer] -> Integer
11 | even x = (x - 2) * fun1 xs
14 2. fun2 :: Integer -> Integer fun2 1 = 0
15 fun2n | even n = n + fun2 (n ‘div‘ 2)
16 | otherwise = fun2 (3 * n + 1)
17 Hint: For this problem you may wish to use the functions
18 iterate and takeWhile. Look them up in the Prelude
19 documentation to see what they do.
22 fun1 :: [Integer] -> Integer
25 | even x = (x - 2) * fun1 xs
28 fun1' :: [Integer] -> Integer
29 fun1' = product . (map (\x -> x - 2)) . filter even
31 fun2 :: Integer -> Integer
33 fun2 n | even n = n + fun2 (n `div` 2)
34 | otherwise = fun2 (3 * n + 1)
36 fun2' :: Integer -> Integer
37 fun2' n = sum $ filter even $ takeWhile (/= 1) $ iterate gen n
38 where gen x | even x = x `div` 2
39 | otherwise = 3 * x + 1
45 | Node Integer (Tree a) a (Tree a)
48 -- generate balanced binary tree using foldr
49 height :: Tree a -> Integer
51 height (Node h _ _ _) = h
53 balanced :: Tree a -> Bool
55 balanced (Node _ lt _ rt) = abs (height lt - height rt) <= 1 &&
56 balanced lt && balanced rt
58 insert :: a -> Tree a -> Tree a
59 insert x Leaf = Node 0 Leaf x Leaf
60 insert x (Node h lt v rt) | h1 < h2 = Node h (insert x lt) v rt
61 | h1 > h2 = Node h lt v (insert x rt)
62 | otherwise = Node (newh + 1) lt v (insert x rt)
65 newh = height (insert x rt)
67 foldTree :: [a] -> Tree a
68 foldTree = foldr f Leaf
69 where f x acc = insert x acc
74 xor bs = foldr f False bs
75 where f False False = False
80 -- implement map as a fold
81 map' :: (a -> b) -> [a] -> [b]
83 where f' x acc = (f x) : acc