計算機プログラムの構造と解釈 第二版 P60 問題2.22
これも、そんな難しくないな。
この二つを求められればいいのさ。
・square-listが逆の順に答えのリストをつくっちゃった、なぜか?
・直したsquare-listがまた上手く動かなかった。なぜか?
1番目の方はlistの入れ方が、右からつめていってっからダメ。
2番目はlistの定義が間違っている。リストの定義ってのははこんなかんじだ。
(cons a (cons b (cons c .....
一応ちゃんと動くものも、2種類作ってみた。
はい実装
#!/usr/local/bin/gosh ;; -*- coding: utf-8 -*- (use ggc.debug.trace) (use math.mt-random) (define nil '()) (define (square x) (* x x)) (define (square-list items) (define (iter things answer) (if (null? things) answer (iter (cdr things) (cons (square (car things)) answer)))) (iter items nil)) (define (square-list2 items) (define (iter things answer) (if (null? things) answer (iter (cdr things) (cons answer (square (car things)))))) (iter items nil)) (define (square-list3 items) (define (iter things answer) (if (null? things) answer (iter (cdr things) (append answer (list (square (car things))))))) (iter (cdr items) (list (square (car items))))) (define (square-list4 items) (define (iter things answer) (if (null? things) (reverse answer) (iter (cdr things) (cons (square (car things)) answer)))) (iter items nil)) ;; main (define (main args) (display "これだとどんどん右側に詰めていってるよね。")(newline) (display "(square-list (list 1 2 3 4))): ") (display (square-list (list 1 2 3 4))) (newline) (display "これはリストの定義としておかしい")(newline) (display "(square-list2 (list 1 2 3 4))): ") (display (square-list2 (list 1 2 3 4))) (newline) (display "(square-list3 (list 1 2 3 4))): ") (display (square-list3 (list 1 2 3 4))) (newline) (display "(square-list4 (list 1 2 3 4))): ") (display (square-list4 (list 1 2 3 4))) (newline) 0)
実行
これだとどんどん右側に詰めていってるよね。 (square-list (list 1 2 3 4))): (16 9 4 1) これはリストの定義としておかしい (square-list2 (list 1 2 3 4))): ((((() . 1) . 4) . 9) . 16) (square-list3 (list 1 2 3 4))): (1 4 9 16) (square-list4 (list 1 2 3 4))): (1 4 9 16)
こんな感じで。