-- Solutions to CSE 341 Haskell Discussion Questions #3 mystery = 1 : map (+2) mystery -- mystery is the list [1,3 ..] -- in other words, all the odd numbes -- version of repeat from the Prelude repeat' :: a -> [a] repeat' x = x : repeat' x -- version of cycle from the Prelude cycle' :: [a] -> [a] cycle' xs = xs ++ cycle xs {- Give a recursive definition of a variable doubles whose first element is 10, and whose n-th element is twice the n-1 st, i.e [10, 20, 40, 80, 160, 320, ....] Use a helper function doubles_from that returns a list of all the doubles starting at n. -} doubles :: [Integer] doubles = doubles_from 10 doubles_from :: Integer -> [Integer] doubles_from n = n : doubles_from (2*n) -- other versions of doubles doubles2 :: [Integer] doubles2 = 10 : map (*2) doubles -- using iterate: doubles3 :: [Integer] doubles3 = iterate (*2) 10 {- Write a Haskell function to return the infinite list of amounts of money you have every year, assuming you start with $100 and get paid 5% interest, compounded yearly. -} -- simple but not general version: dollars :: [Double] dollars = 100 : map (\d -> 1.05*d) dollars -- or using iterate: idollars = iterate (1.05*) 100 -- more general recursive version: better_dollars :: [Double] better_dollars = dollar_growth 100.0 0.05 dollar_growth :: Double -> Double -> [Double] dollar_growth p rate = p : dollar_growth (p*(1+rate)) rate {- infinite list of all integers, ordered in such a way that you can find any given integer after searching a finite number of elements -} ints :: [Integer] ints = 0 : intsfrom 1 intsfrom n = n : (-n) : intsfrom (n+1) {- or an alternate version: -} otherints = 0: interleave [1..] [-1, -2 ..] interleave (x:xs) (y:ys) = x : y : interleave xs ys