暇シリーズ

まとめて解答していく!

問題 1.41

(define (inc n)
  (+ n 1))

(define (double f)
  (lambda (x) (f (f x))))

問題省略、解説省略。

gosh> (((double (double double)) inc) 5)
21

double で 2 回
これを double で 4 回。
これをさらに double なので 16 回。
5 に 16 回 inc するので 21。

問題1.42

(define (inc x)
  (+ x 1))

(define (square x)
  (* x x))

(define (compose f g)
  (lambda (x) (f (g x))))
gosh> ((compose square inc) 6)
49

6 に inc して square するので 49。

問題 1.43

(define (inc x)
  (+ x 1))

(define (square x)
  (* x x))

(define (compose f g)
  (lambda (x) (f (g x))))

(define (repeated f n)
  (if (= n 1)
      f
      (compose f (repeated f (- n 1)))))

簡単すぎて特記事項なし。

gosh> ((repeated square 2) 5)
625

問題1.44

(define (average x y z)
  (/ (+ x y z) 3))

(define (square x)
  (* x x))

;;

(define (compose f g)
  (lambda (x) (f (g x))))

(define (repeated f n)
  (if (= n 1)
      f
      (compose f (repeated f (- n 1)))))

;;

(define dx 0.00001)

(define (smoothing f)
  (lambda (x) (average (f (- x dx)) (f x) (f (+ x dx)))))

(define (n-fold-smoothing-function f n)
  ((repeated smoothing n) f))

問題文のとおりに実装。

gosh> ((smoothing square) 10)
100.00000000006666
gosh> ((smoothing square) 5)
25.000000000066663
gosh> ((n-fold-smoothing-function square 3) 10)
100.00000000019999
gosh> ((n-fold-smoothing-function square 5) 10)
100.00000000033333