SICP-2nd-Edition-Exercise-1.30-Haskell

From Boozled

Jump to: navigation, search

Contents

Exercise 1.30 From SICP in Haskell

Details from SICP are here

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:

  1. (define (sum term a next b)
  2.   (define (iter a result)
  3.     (if <??>
  4.         <??>
  5.         (iter <??> <??>)))
  6.   (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

  1. module Main where
  2. import Text.Printf
  3. --inc    :: Integer -> Integer
  4. --step   :: Integer -> Integer
  5. --mysum  :: Integer -> Integer -> Integer
  6. --iter   :: Integer -> Integer -> (Integer -> a) -> (Integer -> b) -> Integer -> Integer
  7.  
  8. main = printf "res==%d\n\n" (mysum2 (1::Integer) (10::Integer))
  9.  
  10. inc  a = a
  11. step a = (+) a 1
  12.  
  13. mysum2 a b =
  14.       iter a b inc step 0
  15.  
  16. mysum a b =
  17.   let
  18.       inc x = x
  19.       step y = y + 1
  20.   in
  21.       iter a b inc step 0
  22.  
  23. iter a b incr stepper acc =
  24.   if a > b
  25.       then acc
  26.       else iter (stepper a) b incr stepper (acc + (incr a) )

Parent Course

6.001_Structure_and_Interpretation_of_Computer_Programs

Further Reading

Personal tools