summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorrsiddharth <s@ricketyspace.net>2017-10-29 03:54:29 +0000
committerrsiddharth <s@ricketyspace.net>2017-10-29 03:54:29 +0000
commit8cbbb070f630e0eb23b152ffb4e318a2fdba02d0 (patch)
treefd13926dff5283d76acda85de0b91c9305871e37
parent1b3b4fa04de06786427cf3753962236d28a40ecd (diff)
net: (1.32) Add iterative version of accumulator.
* net/ricketyspace/sicp/one/thirtytwo.scm (accumulate-iter, product-iter) (factorial-iter, sum-iter, simpson-iter): New functions.
-rw-r--r--net/ricketyspace/sicp/one/thirtytwo.scm33
1 files changed, 32 insertions, 1 deletions
diff --git a/net/ricketyspace/sicp/one/thirtytwo.scm b/net/ricketyspace/sicp/one/thirtytwo.scm
index 6287353..f76b2ed 100644
--- a/net/ricketyspace/sicp/one/thirtytwo.scm
+++ b/net/ricketyspace/sicp/one/thirtytwo.scm
@@ -3,7 +3,7 @@
;;;; <https://creativecommons.org/licenses/by-sa/4.0/>.
(define-module (net ricketyspace sicp one thirtytwo)
- #:export (factorial simpson))
+ #:export (factorial factorial-iter simpson simpson-iter))
(define (accumulate combiner null-value term a next b)
(if (> a b)
@@ -11,17 +11,35 @@
(combiner (term a)
(accumulate combiner null-value term (next a) next b))))
+(define (accumulate-iter combiner null-value term a next b)
+ (define (iter a result)
+ (if (> a b)
+ result
+ (iter (next a) (combiner (term a) result))))
+ (iter a null-value))
+
(define (product term a next b)
(accumulate * 1 term a next b))
+(define (product-iter term a next b)
+ (accumulate-iter * 1 term a next b))
+
(define (factorial n)
(let ((term (lambda (x) x))
(next (lambda (x) (1+ x))))
(product term 1 next n)))
+(define (factorial-iter n)
+ (let ((term (lambda (x) x))
+ (next (lambda (x) (1+ x))))
+ (product-iter term 1 next n)))
+
(define (sum term a next b)
(accumulate + 0 term a next b))
+(define (sum-iter term a next b)
+ (accumulate-iter + 0 term a next b))
+
(define (simpson f a b n)
(let* ((h (/ (- b a) (* 1.0 n)))
(y (lambda (k) (+ a (* k h))))
@@ -34,3 +52,16 @@
(next (lambda (k) (1+ k))))
(* (/ h 3.0)
(sum term 0 next n))))
+
+(define (simpson-iter f a b n)
+ (let* ((h (/ (- b a) (* 1.0 n)))
+ (y (lambda (k) (+ a (* k h))))
+ (ce (lambda (k) ;coefficient
+ (cond ((or (= k 0) (= k n)) 1)
+ ((even? k) 2)
+ (else 4))))
+ (term (lambda (k)
+ (* (ce k) (f (y k)))))
+ (next (lambda (k) (1+ k))))
+ (* (/ h 3.0)
+ (sum-iter term 0 next n))))