我正在从事SICP练习2.59,该练习要求读者“为集合的无序列表表示实现并集操作” 。两组的并集-用A∪B表示-是元素在A,B或A和B两者中的集合。
这是我为执行此操作而编写的代码:
(define (element-of-set? x set)
(cond ((null? set) #f)
((equal? x (car set)) #t)
(else (element-of-set? x (cdr set)))))
(define (union a b)
(cond ((null? a) b)
((null? b) a)
(element-of-set? (car b) a)
(union a (cdr b))
(else (cons (car b) a))))
我在几组偶数(define odds '(1 3 5)) (define evens '(0 2 4 6)) (union odds evens)
上对其进行了测试,并且当预期输出为(1 3 5)
时得到了(1 3 5 0 2 4 6)
的输出。谁能解释为什么我得到此输出以及如何重写代码以得到预期的输出?
这是一个有效的联合程序示例:
(define (union-set s1 s2)
(if (null? s1)
s2
(let
((e (car s1)))
(union-set
(cdr s1)
(if (element-of-set? e s2) s2 (cons e s2))))))
答案 0 :(得分:2)
在您的else
子句中,您不会调用union
,因此您丢失了cdr b
中的所有内容。
也许:
(else (union (cons (car b) a) (cdr b)))
答案 1 :(得分:2)
您的代码有两个问题:
()
这应该解决它:
(define (union a b)
(cond ((null? a) b)
((null? b) a)
((element-of-set? (car b) a)
(union a (cdr b)))
(else (cons (car b) (union a (cdr b))))))
或者,如果您想保留 exact 的顺序与问题的示例输出中的顺序相同:
(define (union a b)
(cond ((null? a) b)
((null? b) a)
((not (element-of-set? (car a) b))
(cons (car a) (union (cdr a) b)))
(else (union (cdr a) b))))