From: Ramakrishnan Muthukrishnan Date: Fri, 19 Dec 2014 16:27:37 +0000 (+0530) Subject: hw #4: exercise 1 solution X-Git-Url: https://git.rkrishnan.org/%5B/frontends/%22news.html/something?a=commitdiff_plain;h=9f03ad8570314eafd70d3d5fab4a2704851bc588;p=yorgey.git hw #4: exercise 1 solution --- diff --git a/hw4/04-higher-order.pdf b/hw4/04-higher-order.pdf new file mode 100644 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 index 0000000..efeb3f9 --- /dev/null +++ b/hw4/hw4.hs @@ -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