SICP-2nd-Edition-Exercise-1.31-Haskell
From Boozled
Contents |
Exercise 1.31 From SICP in Haskell
a. The (sum) procedure is only the simplest of a vast number of similar abstractions that can be captured as higher-order procedures.55 Write an analogous procedure called (product) that returns the product of the values of a function at points over a given range. Show how to define (factorial) in terms of (product). Also use (product) to compute approximations to π using the formula 52
b. If your (product) procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.
Attempt
Part a
Please read through the Scheme version of this exercise to see my train of thought
I found this exercise quite hard in Haskell. This was due to me struggling with trying to understand the way Haskell handles types etc. So far, for me, it appears that Haskells strong typing is a real pain to use. I cannot relate it to anything I have done in the past so it's taking some getting used to.
I'm hoping that I learn more Haskell this gets a lot easier. If it doesn't then I think I may need to try a language other than Haskell to do this in.
I also noticed that DrScheme computed the result a lot faster than Haskell and used a lot less RAM. For really big numbers Haskell would run out of stack space rapidly. If I increased it it took a long time to run. I think this could be attributed to my rubbish Haskell skills. I will take another attempt at this to remove the temporary variables etc. I think the way i have written this is recursive rather than iterative hence the problems.
Part b
Please look in the book at the recursive sum algorithm.
Haskell
module Main where
import Text.Printf
--jw :: Integer -> Integer--accumulator :: (Integer -> Integer) -> Integer -> Integer -> (Integer -> Integer) -> (Integer -> Integer) -> Integer -> Integerjwp :: Double -> Double
jwn :: Double -> Double
accumulator :: (Double -> Double) -> Double -> Double -> (Double -> Double) -> (Double -> Double) -> Double -> Double
main =dolet result = (johnwallis (2::Double) 200000) * 4.0
printf "\n"printf "\tresult==%f\n" resultprintf "\n"johnwallis a b =letap = a + 2
inc x = xstep y = y + 2
in(jwstratp a b inc step 1 ) * (jwstratn ap b inc step 1 )
jwp n = n/(n + 1.0)
jwn n = n/(n - 1.0)
jwstratp = accumulator jwpjwstratn = accumulator jwnaccumulator op a b incr stepper acc =letp = acc * (op (incr a))
a1 = stepper ainif a1 > b
then pelse accumulator op a1 b incr stepper p
Parent Course
6.001_Structure_and_Interpretation_of_Computer_Programs

