1.3.2 lambdaを使う手続きの構築
- 手続きを作り出す特殊形式lambda
- 一般的にlambdaは、手続きに名前がつかない他は、defineと同様に手続きを作り出すのに使う
- let式は基盤となるlambda作用の構文シュガーに過ぎない
- let式で指定された変数の有効範囲はletの本体である
- 局所変数の値を用意する式が、局所変数と同じ名前の変数に依存している時、問題となる
問題1.31
(define (product term a next b)
(if (> a b)
1
(* (term a)
(product term (next a) next b))))
(define (factorial n)
(define (inc x) (+ x 1))
(define (identity x) x)
(product identity 1 inc n))
(factorial 6)
(define (normal-factorial n)
(if (= n 1)
1
(* n (normal-factorial (- n 1)))))
(normal-factorial 6)
(define (wallis n)
(define (square x) (* x x))
(define (next x) (+ x 1))
(define (term x)
(/ (* (* x 2) (* (+ x 1) 2))
(square (+ (* x 2) 1))))
(product term 1.0 next n))
(wallis 100)
(wallis 1000)
(wallis 10000)
(wallis 100000)
(use math.const)
pi/4
(define (product term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (* a result))))
(iter a 1)) ||<**問題1.32
>|schme|
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumulate combiner null-value term (next a) next b))))1
(define (identity x) x)
(define (inc x) (+ x 1))
(accumulate * 1 identity 1 inc 5)
(accumulate + 0 identity 1 inc 10)
(define (accumulate combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner result (term a)))))
(iter a null-value))
(accumulate * 1 identity 1 inc 5)
(accumulate + 0 identity 1 inc 10)
問題1.33
(define (filtered-accumulate filter combiner null-value term a next b)
(if (> a b)
null-value
(if (filter a)
(combiner (term a)
(filtered-accumulate filter combiner null-value term (next a) next b))
(filtered-accumulate filter combiner null-value term (next a) next b))))
(define (accumulate combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner result (term a)))))
(iter a null-value))
(define (filtered-accumulate filter combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(if (filter a)
(iter (next a) (combiner result (term a)))
(iter (next a) result))))
(iter a null-value))
(define (prime? n)
(if (= n 1)
#f
(= n (smallest-divisor n))))
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond [(> (square test-divisor) n) n]
[(divides? test-divisor n) test-divisor]
[else (find-divisor n (+ test-divisor 1))]))
(define (divides? a b)
(= (remainder b a) 0))
(define (square n)
(* n n))
(define (identity n) n)
(define (inc n) (+ 1))
(define (sum-of-prime a b)
(filtered-accumulate prime? + 0 identity a inc b))
(sum-of-prime 1 10)
(define (product-of-gcd n)
(define (gcd a b)
(if (= b 0)
a
(gcd b (remainder a b))))
(define (gcd-filter x)
(= (gcd n x) 1))
(filtered-accumulate gcd-filter * 1 identity 1 inc n))
(product-of-gcd 5)
(product-of-gcd 6)
(product-of-gcd 7)
問題1.34
(define (f g)
(g 2))
(define (square x)
(* x x))
(f square)
(f (lambda (z) (* z (+ z 1))))
(f f)
その他
- 再帰を反復に書きなおす感じはだいぶつかめて気がする。
- 前にやった時よりもletの概念がすっと頭に入ってきた気がする。