欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SICP 2.30~2.32 习题答案

程序员文章站 2022-07-14 10:48:48
...
;; 2.30
;(define (square-tree tree)
;  (cond ((null? tree) nil)
;        ((not (pair? tree)) (* tree tree))
;        (else (cons (square-tree (car tree))
;                    (square-tree (cdr tree))))))

;(define (square-tree tree)
;  (map (lambda (sub-tree)
;         (if (pair? sub-tree)
;             (square-tree sub-tree)
;             (* sub-tree sub-tree)))
;       tree))

;; 2.31
(define (square x) (* x x))

(define (tree-map proc tree)
  (cond ((null? tree) nil)
        ((not (pair? tree)) (proc tree))
        (else (cons (tree-map proc (car tree))
                    (tree-map proc (cdr tree))))))

(define (square-tree tree) (tree-map square tree))

;(square-tree
; (list 1
;       (list 2 (list 3 4) 5)
;       (list 6 7)))

;; 2.32
(define (subsets s)
  (if (null? s)
      (list nil)
      (let ((rest (subsets (cdr s))))
        (append rest (map (lambda (x) (cons (car s) x)) rest)))))

;(subsets (list 1 2 3))
相关标签: REST Scheme