2008-04-15から1日間の記事一覧

Ex 2.39

(define (reverse xs) (fold-right (lambda (x y) (append y (list x))) nil xs)) (define (reverse xs) (fold-left (lambda (x y) (cons y x)) nil xs))

Ex 2.38

(fold-right / 1 (list 1 2 3)) ;Value: 3/2 <== (1 / (2 / (3 / 1))) (fold-left / 1 (list 1 2 3)) ;Value: 1/6 <== (((1 / 3) / 2) / 1) (fold-right cons nil (list 1 2 3)) ;Value: (1 2 3) <== (cons 1 (cons 2 (cons 3 nil))) (fold-left cons nil (l…

Ex 2.37

(define (matrix-*-vector m v) (map (lambda (x) (dot-product x v) m)) (define (transpose mat) (accumulate-n cons nil mat)) (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map (lambda (x) (map (lambda (y) (dot-product x y)) cols))…

Ex 2.36

(define (accumulate-n op init xs) (if (null? (car xs)) nil (cons (accumulate op init (accumulate (lambda (x xs) (cons (car x) xs)) nil xs)) (accumulate-n op init (accumulate (lambda (x xs) (cons (cdr x) xs)) nil xs)))))

Ex 2.35

(define (count-leaves t) (accumulate + 0 (map (lambda (x) (if (pair? x) (count-leaves x) 1)) t))) accumulate で実装するというので、まず浮かんだのは fringe を使って木をリストにたたんでから長さを計るというものだったのだけれど、 accumulate の…

Ex 2.34

(define (horner-eval x coefs) (accumulate (lambda (coef higher) (+ coef (* x higher))) 0 coefs))

Ex 2.33

ここからは accumulate が定義された環境が前提になる、のか。 (define (map f xs) (accumulate (lambda (x y) (cons (f x) y)) nil xs)) (define (append xs ys) (accumulate cons ys xs)) (define (length xs) (accumulate (lambda (x y) (+ 1 y)) 0 xs) a…

Ex 2.32

これは以前悩んだことがあるから楽勝 (コードを書くのは)。 (define (subsets s) (if (null? s) (list s) (let ((rest (subsets (cdr s)))) (append rest (map (lambda (x) (cons (car s) x)) rest))))) なぜこれでよいか、に対する明快な説明...ってのは難…

Ex 2.31

(define (tree-map f t) (map (lambda (x) (if (pair? x) (tree-map f x) (f x))) t))

Ex 2.30

map 使用: (define (square-tree t) (map (lambda (x) (if (pair? x) (square-tree x) (square x))) t)) map 不使用: (define (square-tree t) (cond (null? t) t) ((not (pair? t)) (square t)) (else (cons (square-tree (car t)) (square-tree (cdr t))))…

Ex 2.29

かなり悩んでいる。とりあえず経過を。a. (define (left-branch m) (car m)) (define (right-branch m) (car (cdr m))) (define (branch-length b) (car b)) (define (branch-structure b) (car (cdr b))) b. (define (total-weight m) (define (weight b) (…

Ex 2.28

(define (fringe xs) (cond ((null? xs) xs) ((not (pair? (car xs))) (cons (car xs) (fringe (cdr xs)))) (else (append (fringe (car xs)) (fringe (cdr xs)))))) という解答を作ったのだが、テキストを読み進めるとわかるとおり以下で足りるらしい: (def…

Ex 2.27

(define (deep-reverse xs) (if (or (null? xs) (not (pair? xs))) xs (append (deep-reverse (cdr xs)) (list (deep-reverse (car xs))))))

Ex 2.26

答えは順に (1 2 3 4 5 6) ((1 2 3) 4 5 6) ((1 2 3) (4 5 6))

Ex 2.25

これは、いやがらせ問題、だろうか?答えは順に、 (car (cdr (car (cdr (cdr <>))))) (car (car <>)) (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr <>))))))))))))