【发布时间】:2016-03-14 07:06:36
【问题描述】:
我的计算机科学课有两个问题需要帮助。问题如下。
写一个包含所有的函数?它使用两个数字列表,如果第一个列表包含第二个列表的所有元素,则返回 true,否则返回 false。为简单起见,假设两个列表都不包含多次相同的元素。
编写一个函数 common-elements,它接受两个数字列表并返回两个列表中出现的所有元素的列表。
到目前为止,我有以下代码:
(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 号也有同样的问题,需要帮助。
【问题讨论】:
-
为什么是
(check-expect (contains-all? (list 1 2 3) empty) false)?它应该根据规范返回true,因为第一个列表包含第二个列表的所有元素(假设第二个是empty)。而且,既然您使用的是 DrRacket,为什么要以类似 BASIC 的格式粘贴程序?请使用适当的缩进,或简单地粘贴 DrRacket 编辑器中的代码。 -
我假设列表已排序(否则您必须先对它们进行排序)。如果 (first lon) not 的 lon2。仅当 (first lon) = (first lon2) 时才跳过两者。
标签: recursion racket generative