2015/10/19

SICP 問題 2.22

(define (square-list items)
  (define (iter things answer)
    (if (null? things)
        answer
        (iter (cdr things)
              (cons (square (car things))
                    answer))))
  (iter items nil))
;; iter内でのconsで(square (car things))とanswerを引数として取っている.
;; この場,次のcdrでconsされるのは(square (car (cdr things))) と((square (car things)) answer).
;; ここで順番が逆になっている.
;; このまま続けていくと欲しかったリストの逆順が返される.

(define (square-list items)
  (define (iter things answer)
    (if (null? things)
        answer
        (iter (cdr things)
              (cons answer
                    (square (car things))))))
  (iter items nil))
;; 始めのconsで作られるのは(() . 1).
;; 次の繰り返しでconsすると((() . 1) . 2)ができる.
;; 始めのconsで作られたドット対を要素としたドット対ができる.
;; これを繰り返すのでうまくいかない.

© 2022 wat-aro