commit 4a763364f95f99c0a6597d5f9a8049a741a5d048
parent d1f476d505795e81c81b09753a0eaba294a03e06
Author: Yuval Langer <yuval.langer@gmail.com>
Date: Mon, 10 Apr 2023 14:35:21 +0300
Add solutions to exercise 1.30 and 1.31.
Diffstat:
4 files changed, 123 insertions(+), 0 deletions(-)
diff --git a/sicp/solutions/1_30.scm b/sicp/solutions/1_30.scm
@@ -0,0 +1,26 @@
+(define-library (sicp solutions 1_30)
+ (import (scheme base))
+ (export
+ linear-recursive-sum
+ iterative-sum
+ )
+
+ (begin
+ (define (linear-recursive-sum term a next b)
+ (if (> a b)
+ 0
+ (+ (term a)
+ (linear-recursive-sum term
+ (next a)
+ next
+ b))))
+
+ (define (iterative-sum term a next b)
+ (define (iter a result)
+ (if (> a b)
+ result
+ (iter (next a)
+ (+ (term a)
+ result)))
+ )
+ (iter a 0))))
diff --git a/sicp/solutions/1_31.scm b/sicp/solutions/1_31.scm
@@ -0,0 +1,51 @@
+(define-library (sicp solutions 1_31)
+ (import (scheme base))
+ (export
+ iterative-product
+ recursive-product
+ factorial
+ tau-approximation
+ )
+
+ (begin
+ (define (identity x) x)
+ (define (1+ x) (+ 1 x))
+ (define (1- x) (- 1 x))
+
+ (define (iterative-product term a next b)
+ (define (iter a result)
+ (if (> a b)
+ result
+ (iter (next a)
+ (* (term a)
+ result))))
+ (iter a 1))
+
+ (define (factorial n)
+ (iterative-product identity
+ 1
+ 1+
+ n))
+
+
+ (define (tau-approximation n)
+ (* 8
+ (iterative-product (lambda (x)
+ (/ (if (odd? x)
+ (+ 1 x)
+ (+ 2 x))
+ (if (odd? x)
+ (+ 2 x)
+ (+ 1 x))))
+ 1
+ 1+
+ n)))
+
+ (define (recursive-product term a next b)
+ (if (> a b)
+ 1
+ (* (term a)
+ (recursive-product term
+ (next a)
+ next
+ b))))))
diff --git a/sicp/tests/1_30.scm b/sicp/tests/1_30.scm
@@ -0,0 +1,17 @@
+(define-library (sicp tests 1_30)
+ (import (scheme base))
+ (import (srfi :64))
+ (import (sicp solutions 1_30))
+
+ (begin
+ (test-begin "1.30")
+ (test-equal
+ (iterative-sum (lambda (x) (* x x))
+ 0
+ (lambda (x) (+ 1 x))
+ 10)
+ (linear-recursive-sum (lambda (x) (* x x))
+ 0
+ (lambda (x) (+ 1 x))
+ 10))
+ (test-end "1.30")))
diff --git a/sicp/tests/1_31.scm b/sicp/tests/1_31.scm
@@ -0,0 +1,29 @@
+(define-library (sicp tests 1_31)
+ (import (scheme base))
+ (import (srfi :1))
+ (import (srfi :64))
+ (import (sicp solutions 1_31))
+
+ (begin
+ (define fac-10
+ (reduce *
+ 1
+ (iota 10 1)))
+
+ (test-begin "1.31")
+ (test-equal
+ fac-10
+ (factorial 10))
+ (test-equal
+ 628
+ (floor (* 100 (tau-approximation 1000))))
+ (test-equal
+ (iterative-product (lambda (x) (* x x))
+ 1
+ (lambda (x) (+ 2 x))
+ 10)
+ (recursive-product (lambda (x) (* x x))
+ 1
+ (lambda (x) (+ 2 x))
+ 10))
+ (test-end "1.31")))