learning-sicp

My embarrassing half assed SICP run.
git clone https://kaka.farm/~git/learning-sicp
Log | Files | Refs

exercise-31.scm (1260B)


      1 (define-library (sicp solutions chapter-1 exercise-31)
      2   (import (scheme base))
      3   (export
      4    iterative-product
      5    recursive-product
      6    factorial
      7    tau-approximation
      8    )
      9 
     10   (begin
     11     (define (identity x) x)
     12     (define (1+ x) (+ 1 x))
     13     (define (1- x) (- 1 x))
     14 
     15     (define (iterative-product term a next b)
     16       (define (iter a result)
     17         (if (> a b)
     18             result
     19             (iter (next a)
     20                   (* (term a)
     21                      result))))
     22       (iter a 1))
     23 
     24     (define (factorial n)
     25       (iterative-product identity
     26                          1
     27                          1+
     28                          n))
     29 
     30 
     31     (define (tau-approximation n)
     32       (* 8
     33          (iterative-product (lambda (x)
     34                     (/  (if (odd? x)
     35                             (+ 1 x)
     36                             (+ 2 x))
     37                         (if (odd? x)
     38                             (+ 2 x)
     39                             (+ 1 x))))
     40                   1
     41                   1+
     42                   n)))
     43 
     44     (define (recursive-product term a next b)
     45       (if (> a b)
     46           1
     47           (* (term a)
     48              (recursive-product term
     49                                 (next a)
     50                                 next
     51                                 b))))))