1.3.3 Procedures as General Methods
タイトル修正。
1.34
(define (f g) (g 2))
MzSchemeで。
:mz (f f) procedure application: expected procedure, given: 2; arguments were: 2
; (f f) ; => (f 2) ; => (2 2)
1.35 (fixed-pointで黄金比)
(define tolerance 0.00001)
(define (fixed-point f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))(fixed-point (lambda (x) (+ 1 (/ x))) 1)
1.36 (fixed-pointを途中経過の表示つきで)
(define (fixed-point/progress f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(let ((next (f guess)))
(display next)
(newline)
(if (close-enough? guess next)
next
(try next))))
(display first-guess)
(newline)
(try first-guess))
(fixed-point/progress (lambda (x) (/ (log 1000) (log x))) 10)
1.37 (continued fraction)
できるだけ今までに出てきたものだけを使って書くようにしてるけど、ここはdoを使わせてもらった。
; Recursive
(define (cont-frac n d k)
(define (cont-frac-sub i)
(if (> i k)
0
(/ (n i)
(+ (d i) (cont-frac-sub (+ i 1))))))
(cont-frac-sub 1))
; Iterative
(define (cont-frac n d k)
(define (cont-frac-iter i acc)
(if (= i 0)
acc
(cont-frac-iter (- i 1)
(/ (n i)
(+ (d i) acc)))))
(cont-frac-iter k 0))
(define (approximate-golden-ratio times)
(define (golden-ratio/cont-frac k)
(cont-frac (lambda (i) 1.0)
(lambda (i) 1.0)
k))
(do ((i 1 (+ i 1))) ((> i times))
(print (golden-ratio/cont-frac i))
(newline)))
1.38 (eの近似)
(define (approximate-natural-log-base k)
(+ 2 (cont-frac (lambda (i) 1.0)
(lambda (i)
(if (= (remainder i 3) 2)
(* (+ (quotient i 3) 1) 2)
1))
k)))
1.39 (tanの近似)
(define (tan-cf x k)
(- (cont-frac (lambda (i) (- (expt x (if (= i 1) 1 2))))
(lambda (i) (- (* i 2) 1))
k)))