SICP 2.33~2.39习题答案
程序员文章站
2022-07-14 10:50:06
...
(define (filter predicate sequence) (cond ((null? sequence) nill) ((predicate (car sequence)) (cons (car sequence) (filter predicate (cdr sequence)))) (else (filter predicate (cdr sequence))))) (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define (enumerate-interval low high) (if (> low high) nil (cons low (enumerate-interval (+ low 1) high)))) ;2.33 (define (map p sequence) (accumulate (lambda (x y) (cons (p x) y)) nil sequence)) ;(map (lambda (x) (* x x)) (list 1 2 3 4)) (define (append seq1 seq2) (accumulate cons seq2 seq1)) ;(append (list 1 2 3) (list 3 4 5)) (define (length sequence) (accumulate (lambda (x y) (+ 1 y)) 0 sequence)) ;(length (list 1 2 3)) ;2.34 (define (horner-eval x coefficient-sequence) (accumulate (lambda (this-coeff higher-terms) (+ this-coeff (* x higher-terms))) 0 coefficient-sequence)) ;(horner-eval 2 (list 1 3 0 5 0 1)) ;2.35 (define (count-leaves t) (accumulate + 0 (map (lambda (x) (if (pair? x) (count-leaves x) 1)) t))) ;(define x (cons (list 1 2) (list 3 4))) ;(count-leaves (list x x)) ;2.36 (define (accumulate-n op init seqs) (if (null? (car seqs)) nil (cons (accumulate op init (map car seqs)) (accumulate-n op init (map cdr seqs))))) (define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12))) ;(accumulate-n + 0 s) ;; 2.38 (define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial sequence)) (define (fold-right op initial sequence) (accumulate op initial sequence)) ;(fold-right / 1 (list 1 2 3)) ;(fold-left / 1 (list 1 2 3)) ;(fold-right list nil (list 1 2 3)) ;(fold-left list nil (list 1 2 3)) ;;2.39 (define (reverse sequence) (fold-right (lambda (x y) (append y (cons (if (pair? x) (reverse x) x) nil))) nil sequence)) (define (reverse sequence) (fold-left (lambda (x y) (append (cons (if (pair? y) (reverse y) y) nil) x)) nil sequence)) ;(reverse (list 1 2 3 4 5 6))
2.37中的线性代数都已经忘光了,略过。
2.38的答案是,op要符合 a op b = b op a 的原则,如+,*。
下一篇: eval解析JSON中的注意点