对于我的作业,给定一个测试和一个操作,我必须计算一个列表,其中操作只对通过测试的元素执行。一个例子是:(selective-map缺点?Length (list (list 1 2) empty (list 3)) => (list 2 1)
我有一点麻烦,试图删除我的失败我的测试。到目前为止我只有
(define (testfunc test lst2)
(cond
[(null? lst2) null]
[(false? (map (compose test) (first lst2))) (remove* (list (first lst2)) (lst2))]
[else (cons (first lst2) (testfunc test (rest lst2)))]))
,当我输入下面的代码来测试我的代码(testfunc cons? (list (list 1 2) '() (list 3)))
时,列表没有改变。是不是有什么我看错了?
递归是错误的(您必须测试每个元素上的谓词,为什么是map
?),这不是删除元素的正确方法,testfunc
与selective-map
不一样,它们甚至没有收到相同数量的参数。我们再试一次,从头开始:
(define (selective-map test proc lst)
(cond
[(null? lst) null]
[(not (test (first lst)))
; to remove an element we simply don't add it to the output list
(selective-map test proc (rest lst))]
[else
; on the other hand, an element that passes the test is consed to the output list
(cons (proc (first lst)) (selective-map test proc (rest lst)))]))
一个更习惯的解决方案是使用折叠过程,而不是显式递归:
(define (selective-map test proc lst)
(foldr (lambda (e acc)
(if (test e)
(cons (proc e) acc)
acc))
null
lst))
无论哪种方式,它都按预期工作:
(selective-map cons? length (list (list 1 2) empty (list 3)))
=> '(2 1)