SICP-2nd-Edition-Exercise-1.30-Haskell
From Boozled
Contents |
Exercise 1.30 From SICP in Haskell
The (sum) procedure above generates a linear recursion. The procedure can be rewritten so that the sum is performed iteratively. Show how to do this by filling in the missing expressions in the following definition:
(define (sum term a next b)
(define (iter a result)
(if <??>
<??>
(iter <??> <??>)))
(iter <??> <??>))
Attempt
Disclaimer: I am not a Haskell programmer and I am sure this is obvious from my attempt below.
Compared to Scheme my attempt feels too imperative so I think it may take a while to get used to Haskell in particular for my Haskell to become more idiomatic. You will also see that I played around with a few ways to do this i.e. global functions for inc and step etc. I have also left in some function definitions that I played with.
Haskell
module Main where
import Text.Printf
--inc :: Integer -> Integer--step :: Integer -> Integer--mysum :: Integer -> Integer -> Integer--iter :: Integer -> Integer -> (Integer -> a) -> (Integer -> b) -> Integer -> Integermain = printf "res==%d\n\n" (mysum2 (1::Integer) (10::Integer))
inc a = astep a = (+) a 1
mysum2 a b =iter a b inc step 0mysum a b =letinc x = xstep y = y + 1
initer a b inc step 0iter a b incr stepper acc =if a > b
then accelse iter (stepper a) b incr stepper (acc + (incr a) )
Parent Course
6.001_Structure_and_Interpretation_of_Computer_Programs

