灯下 登录
计算机科学 / SICP / 2.2.2 Hierarchical Structures

Exercise 2.32 · 习题

Exercise 2.32: We can represent a set as a list
of distinct elements, and we can represent the set of all subsets of the set as
a list of lists. For example, if the set is (1 2 3), then the set of
all subsets is (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)). Complete the
following definition of a procedure that generates the set of subsets of a set
and give a clear explanation of why it works:

(define (subsets s)

(if (null? s)

(list nil)

(let ((rest (subsets (cdr s))))

(append rest (map ⟨??⟩ rest)))))

练习 2.32:我们可以用不同元素的表来表示一个集合,并可以用表的表来表示该集合的所有子集的集合。例如,若集合为 (1 2 3),则所有子集的集合为 (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3))。补全下列过程的定义,该过程生成一个集合的所有子集的集合,并给出一个清晰的解释说明它为何正确:

(define (subsets s)
(if (null? s)
(list nil)
(let ((rest (subsets (cdr s))))
(append rest (map ⟨??⟩ rest)))))

Racket #lang sicp
(define (subsets s)
 (if (null? s)
 (list nil)
 (let ((rest (subsets (cdr s))))
 (append rest (map ⟨??⟩ rest)))))