]> git.rkrishnan.org Git - yorgey.git/blob - hw4/hw4.hs
hw #4: exercise 1 solution
[yorgey.git] / hw4 / hw4.hs
1 module Hw4 where
2
3 -- wholemeal programming
4 {- |
5
6 1. fun1 :: [Integer] -> Integer
7 fun1 [] = 1
8 fun1 (x:xs)
9      | even x    = (x - 2) * fun1 xs
10      | otherwise = fun1 xs
11
12 2. fun2 :: Integer -> Integer fun2 1 = 0
13    fun2n | even n = n + fun2 (n ‘div‘ 2)
14          | otherwise = fun2 (3 * n + 1)
15 Hint: For this problem you may wish to use the functions
16       iterate and takeWhile. Look them up in the Prelude
17       documentation to see what they do.
18 -}
19
20 fun1 :: [Integer] -> Integer
21 fun1 [] = 1
22 fun1 (x:xs)
23      | even x    = (x - 2) * fun1 xs
24      | otherwise = fun1 xs
25
26 fun1' :: [Integer] -> Integer
27 fun1' = product . (map (\x -> x - 2)) . filter even
28
29 fun2 :: Integer -> Integer
30 fun2 1 = 0
31 fun2 n | even n = n + fun2 (n `div` 2)
32        | otherwise = fun2 (3 * n + 1)
33
34 fun2' :: Integer -> Integer
35 fun2' n = sum $ filter even $ takeWhile (/= 1) $ iterate gen n
36     where gen x | even x = x `div` 2
37                 | otherwise = 3 * x + 1