我的计算机科学课有两个问题需要帮助。问题如下。
写一个函数 contains-all? 它使用两个数字列表,如果第一个列表包含第二个列表的所有元素,则返回 true,否则返回 false。为简单起见,假设两个列表都没有多次包含相同的元素。
编写一个函数 common-elements,它接受两个数字列表并返回两个列表中出现的所有元素的列表。
对于数字 1,到目前为止,我有以下代码:
(define (contains-all? lon lon2)
(cond
[(and (empty? lon) (empty? lon2)) true]
[(or (empty? lon) (empty? lon2)) false
[(equal? (first lon) (first lon2)) (contains-all? (rest lon) (rest lon2))]
[else false]))
我的检查预期如下:
(check-expect (contains-all? empty empty) true)
(check-expect (contains-all? empty (list 1 2 3)) false)
(check-expect (contains-all? (list 1 2 3) empty) false)
(check-expect (contains-all? (list 1 2 3) (list 3 2 1)) true)
(check-expect (contains-all? (list 1 2 4 6 8) (list 6 8 4)) true)
(check-expect (contains-all? (list 1 2 8 6) (list 1 2 6 4)) false)
我知道一些检查预期会失败,这就是我需要帮助的地方。
对于问题 2,到目前为止我有这个
(define (common-elements lon lon2)
(cond
[(and (empty? lon) (empty? lon2)) empty]
[(or (empty? lon) (empty? lon2)) empty]
[(equal? (first lon) (first lon2))
(cons (first lon) (common-elements (rest lon) (rest lon2)))]
[(not (equal? (first lon) (first lon2))) (common-elements (first lon) (first lon2))]
;[else (common-elements (first lon) (rest lon2))]))
检查预期如下:
(check-expect (common-elements empty empty) empty)
(check-expect (common-elements empty (list 1 2)) empty)
(check-expect (common-elements (list 1 2) empty) empty)
(check-expect (common-elements (list 1 2 3) (list 1 2 4)) (list 1 2))
(check-expect (common-elements (list 3 2 1) (list 2 1)) (list 2 1))
我对 2 号有同样的问题,需要帮助。