1 {-# OPTIONS_GHC -Wall #-}
5 import qualified Data.List as L
7 -- wholemeal programming
10 1. fun1 :: [Integer] -> Integer
13 | even x = (x - 2) * fun1 xs
16 2. fun2 :: Integer -> Integer fun2 1 = 0
17 fun2n | even n = n + fun2 (n ‘div‘ 2)
18 | otherwise = fun2 (3 * n + 1)
19 Hint: For this problem you may wish to use the functions
20 iterate and takeWhile. Look them up in the Prelude
21 documentation to see what they do.
24 fun1 :: [Integer] -> Integer
27 | even x = (x - 2) * fun1 xs
30 fun1' :: [Integer] -> Integer
31 fun1' = product . (map (\x -> x - 2)) . filter even
33 fun2 :: Integer -> Integer
35 fun2 n | even n = n + fun2 (n `div` 2)
36 | otherwise = fun2 (3 * n + 1)
38 fun2' :: Integer -> Integer
39 fun2' n = sum $ filter even $ takeWhile (/= 1) $ iterate gen n
40 where gen x | even x = x `div` 2
41 | otherwise = 3 * x + 1
47 | Node Integer (Tree a) a (Tree a)
50 -- generate balanced binary tree using foldr
51 height :: Tree a -> Integer
53 height (Node h _ _ _) = h
55 balanced :: Tree a -> Bool
57 balanced (Node _ lt _ rt) = abs (height lt - height rt) <= 1 &&
58 balanced lt && balanced rt
60 insert :: a -> Tree a -> Tree a
61 insert x Leaf = Node 0 Leaf x Leaf
62 insert x (Node h lt v rt) | h1 < h2 = Node h (insert x lt) v rt
63 | h1 > h2 = Node h lt v (insert x rt)
64 | otherwise = Node (newh + 1) lt v (insert x rt)
67 newh = height (insert x rt)
69 foldTree :: [a] -> Tree a
70 foldTree = foldr f Leaf
71 where f x acc = insert x acc
76 xor bs = foldr f False bs
77 where f False False = False
82 -- implement map as a fold
83 map' :: (a -> b) -> [a] -> [b]
85 where f' x acc = (f x) : acc
90 cartProd :: [a] -> [b] -> [(a,b)]
91 cartProd xs ys = [(x, y) | x <- xs, y <- ys]
93 genList :: Integer -> [Integer]
96 sieveSundaram :: Integer -> [Integer]
97 sieveSundaram n = map (\x -> (2*x + 1)) $ (L.\\) xs $ L.sort $ f (cartProd xs xs)
99 f ps = L.nub $ filter (<= n) $ map (\(i,j) -> i + j + 2*i*j) ps