SICPはMITが出してる本で、バイブル的な何からしい。
1章の問題は数学チックなのが多いので、半分くらい飛ばしてしまった。後でやろう。
折角なので、(自分の)答えを載せてみたり。
下のは職場のGaucheで作って(おいおい)、家のMzSchemeで確認。
MzSchemeだと「()」が使えないので、「'()」に変更。
一つMzSchemeで動かないのがあった。処理系依存なコードだったのかしら?
; 2.17 (define (last-pair list) (define (last-pair-itr val list2) (if (null? list2) val (last-pair-itr (car list2) (cdr list2)))) (last-pair-itr (car list)(cdr list))) (last-pair '(1 2 3 4 5 6)) ; 2.18 (define (reverse list) (define (reverse-itr ret list2) (if (null? list2) ret (reverse-itr (cons (car list2) ret) (cdr list2)))) (reverse-itr '() list)) (reverse '(1 2 3 4 5 6)) ; 2.21 (define (square-list-no-map list) (if (null? list) '() (cons (* (car list) (car list)) (square-list-no-map (cdr list))))) (square-list-no-map '(1 2 3 4 5 6)) (define (square-list list) (map (lambda (x)(* x x)) list)) (square-list '(1 2 3 4)) ; 2.22 (define (square-list items) (define (square x)(* x x)) (define (iter things answer) (if (null? things) answer (cons (square (car things)) (iter (cdr things) answer)))) (iter items '())) (square-list '(1 2 3 4 5)) ; 2.23 (define (for-each proc items) (if (null? items) #f (and (proc (car items)) (for-each proc (cdr items))))) ; 2.25 (car (cdr (car (cdr (cdr '(1 3 (5 7) 9)))))) (car (car '((7)))) (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr '(1 (2 (3 (4 (5 (6 7)))))))))))))))))) ; 2.26 (define x (list 1 2 3)) (define y (list 4 5 6)) (append x y) (cons x y) (list x y) ; 2.27 (define x (list (list 1 (list 2 3) (list 4 5)) (list 6 7 8))) (reverse x) (define (deep-reverse list) (define (reverse-itr ret list) (cond ((null? list) ret) ((pair? (car list)) (reverse-itr (cons (reverse-itr '() (car list)) ret) (cdr list))) (else (reverse-itr (cons (car list) ret) (cdr list))))) (reverse-itr '() list)) ; Gaucheでは動いたコード ;(define (deep-reverse list) ; (cond ; ((null? list) '()) ; ((pair? (car list)) (cons (car (cdr (car list)))(car (car list)))) ; (else (cons (deep-reverse (cdr list)) (car list))))) (deep-reverse x) ; 2.28 (define (fringe l2) (cond ((null? l2) '()) ((not (pair? l2)) (cons l2 '())) (else (append (fringe (car l2)) (fringe (cdr l2)))))) (fringe (list x x))
No comments:
Post a Comment