diff --git a/5-recursion.hs b/5-recursion.hs index 6baea90..b7056a9 100644 --- a/5-recursion.hs +++ b/5-recursion.hs @@ -1,19 +1,18 @@ -- Raise x to the power y, using recursion -- For example, power 5 2 = 25 power :: Int -> Int -> Int -power x y = undefined +power x 1 = x +power x y = x * power x (y-1) -- create a list of length n of the fibbonaci sequence in reverse order -- examples: fib 0 = [0] -- fib 1 = [1, 0] --- fib 10 = [55,34,21,13,8,5,3,2,1,1,0] +-- fib 10 = [55,34,21,13,8,5,3,2,1,1,0] -- try to use a where clause fib :: (Num a, Eq a) => a -> [a] fib 0 = [0] fib 1 = [1, 0] -fib n = head prev + head prev2 : prev - where prev = fib (n-1) - prev2 = fib (n-2) +fib n = let all@(x:y:_) = fib (n-1) in (x+y):all -- This is not recursive, but have a go anyway. -- Create a function which takes two parameters, a number and a step @@ -22,9 +21,9 @@ fib n = head prev + head prev2 : prev -- stepReverseSign -3 1 = 4 -- stepReverseSign 1 2 = -3 stepReverseSign :: (Fractional a, Ord a) => a -> a -> a -stepReverseSign num step = ((if num > 0 - then -1 - else 1) * (abs(num) + step)) +stepReverseSign num step + | num < 0 = (abs num) + step + | otherwise = (-1) * (num + step) {- Lets calculate pi. - The Leibniz formula for pi (http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80) @@ -42,7 +41,7 @@ stepReverseSign num step = ((if num > 0 - snd is the number of recursive steps taken to calculate it, after all this chapter is about recursion! - Example: piCalc 0.001 = (3.1420924036835256,2000) - - The piCalc' function is defined as + - The piCalc' function is defined as - piCalc' :: (Ord a, Fractional a, Integral b) => a -> a -> a -> b -> (a, b) - Lots of parameters! - The first parameter is the current denominator from the Leibniz formula @@ -53,7 +52,7 @@ stepReverseSign num step = ((if num > 0 - - Feel free to change the parameter order, what parameters you need etc in order to get this to work for you, - But, of course the output of piCalc should remain as (pi, count) - - + - - You may find the stepReverseSign function handy -} @@ -62,8 +61,6 @@ piCalc tolerance = piCalc' 1 0.0 tolerance 0 piCalc' :: (Ord a, Fractional a, Integral b) => a -> a -> a -> b -> (a, b) piCalc' denom prevPi tolerance count = if abs(newPi - prevPi) < tolerance - then (newPi, count) - else piCalc' (stepReverseSign denom) newPi tolerance (count + 1) - where newPi = prevPi + (4 / denom) - - + then (newPi, count) + else piCalc' (stepReverseSign denom 2) newPi tolerance (count + 1) + where newPi = prevPi + (4 / denom)