]> git.rkrishnan.org Git - yorgey.git/commitdiff
hw #4: exercise 1 solution
authorRamakrishnan Muthukrishnan <ram@rkrishnan.org>
Fri, 19 Dec 2014 16:27:37 +0000 (21:57 +0530)
committerRamakrishnan Muthukrishnan <ram@rkrishnan.org>
Fri, 19 Dec 2014 16:27:37 +0000 (21:57 +0530)
hw4/04-higher-order.pdf [new file with mode: 0644]
hw4/hw4.hs [new file with mode: 0644]

diff --git a/hw4/04-higher-order.pdf b/hw4/04-higher-order.pdf
new file mode 100644 (file)
index 0000000..f0fb2b8
Binary files /dev/null and b/hw4/04-higher-order.pdf differ
diff --git a/hw4/hw4.hs b/hw4/hw4.hs
new file mode 100644 (file)
index 0000000..efeb3f9
--- /dev/null
@@ -0,0 +1,37 @@
+module Hw4 where
+
+-- wholemeal programming
+{- |
+
+1. fun1 :: [Integer] -> Integer
+fun1 [] = 1
+fun1 (x:xs)
+     | even x    = (x - 2) * fun1 xs
+     | otherwise = fun1 xs
+
+2. fun2 :: Integer -> Integer fun2 1 = 0
+   fun2n | even n = n + fun2 (n ‘div‘ 2)
+         | otherwise = fun2 (3 * n + 1)
+Hint: For this problem you may wish to use the functions
+      iterate and takeWhile. Look them up in the Prelude
+      documentation to see what they do.
+-}
+
+fun1 :: [Integer] -> Integer
+fun1 [] = 1
+fun1 (x:xs)
+     | even x    = (x - 2) * fun1 xs
+     | otherwise = fun1 xs
+
+fun1' :: [Integer] -> Integer
+fun1' = product . (map (\x -> x - 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' n = sum $ filter even $ takeWhile (/= 1) $ iterate gen n
+    where gen x | even x = x `div` 2
+                | otherwise = 3 * x + 1