読書会

今日もリモートです。自分の体調不良により。
解は sw@mac のこのエントリから。問題 1.29 はスルーします。次の問題も問題ナシ。

(define (sum term a next b)
  (define (iter a result)
    (if (> a b) result
        (iter (next a) (+ result (term a)))))
  (iter a 0))

素晴しい。で、1.3.2 に入るかと思われたんですが練習問題をいくつか振り返り。

問題 1.31

解の実装が以下。

(define (product term a next b)
  (let iter ((a a) (result 1))
    (if (> a b) result
        (iter (next a) (* result (term a))))))

(define (calc-pi s)
  (define (next n) (+ n 1))
  (* 4 (/ (* (product (lambda (n) (* n 2)) 1 next s)
             (product (lambda (n) (* (+ n 1) 2)) 1 next s))
          (square
           (product (lambda (n) (+ (* n 2) 1)) 1 next s)))))

上記の分子は (/ (* 2 2 4 4 6 6 8 8) 2) との事。項が一つずれる不具合が考えられるとの事ですが、単純にこんなカンジでも良いのかな。

(* 4 (/ (/ (square (product (lambda (n) (* n 2)) 1 next s))
           (* 2 s))
        (square (product (lambda (n) (+ (* n 2) 1)) 1 next s))))

動作確認は略。しかし square したりとか 2 で割りゃ良いとか、若くて賢いって本当にうらやましいッス。

問題 1.33

こんなナニを

;;区間a,bの素数の二乗の和
(define (sum-of-square-of-primes a b)
  (filterd-accumulate sum-of-square 0 prime? identity a inc b))

書き換えてたり。

(define (sum-of-square-of-primes a b)
  (apply + (map square (filter prime? (iota (+ (- b a) 1) a)))))

これ、抽象化という観点で見ると若干微妙な感触あり。one liner で書けるので書きステなソレ、って部分では短く書けてシアワセですが。

問題 1.32

あるいは繰り返しな以下の実装について

(define (accumulate combiner null-value term a next b)
  (let iter ((result (term a)) (a (next a)))
    (if (> a b) result
        (iter (combiner result (term a)) (next a)))))

以下じゃね? なやりとりなど。

(define (accumulate combiner null-value term a next b)
 (let iter ((result null-value) (a a))
   (if (> a b)
       result
       (iter (combiner (term a) result) (next a)))))

これ、リスト操作で考えると若干微妙ですな。比較な条件式は

(> (term a) b)

じゃないと微妙。試してみました。

gosh> (define (accumulate combiner null-value term a next b)
  (let iter ((result (term a)) (a (next a)))
    (if (> (term a) b) result
        (iter (combiner result (term a)) (next a)))))
accumulate
gosh> (accumulate cons '() car '(1 2 3 4 5) cdr 4)
(((1 . 2) . 3) . 4)
gosh> (define (accumulate combiner null-value term a next b)
 (let iter ((result null-value) (a a))
   (if (> (term a) b) result
       (iter (combiner (term a) result) (next a)))))
accumulate
gosh> (accumulate cons '() car '(1 2 3 4 5) cdr 4)
(4 3 2 1)
gosh> 

逆だし。

問題 1.34

置き換えの問題。_(意地悪く)_なあたり、どういった意味なんでしょうか。

ログを確認したところ

問題 1.35 以降は

  • 1.38 〜 1.40
  • 1.44 〜 1.46

をスルーしている模様。不動点、というものについて色々教えを乞う予定。(こら