【发布时间】:2021-06-01 21:59:24
【问题描述】:
我有以下过滤程序:
; (2) filter
(define (filter test sequence)
; return a list of the elements that pass the predicate test
(let ((elem (if (null? sequence) nil (car sequence)))
(rest (if (null? sequence) nil (cdr sequence))))
(cond ((null? sequence) nil)
((test elem) (cons elem (filter test rest)))
(else (filter test rest)))))
下面是一个使用它返回列表的偶数元素的示例:
(define even? (lambda (x) (= (modulo x 2) 0)))
(define sequence '(1 2 3 4 5 8 9 11 13 14 15 16 17))
(filter even? sequence)
; (2 4 8 14 16)
有没有一种简单的方法来使用not 测试来反转选择?例如,我认为以下可能有效:
(filter (not even?) sequence)
但它返回一个错误。我当然可以单独定义odd:
(define odd? (lambda (x) (not (even? x))))
但我尽量不这样做。有没有办法编写odd 过程而不直接定义它,而是直接使用not,就像我在上面尝试做的那样?
【问题讨论】:
-
我感觉到你的痛苦,但你真的必须像Scheme一样使用Scheme。
nil不是 Scheme 中的空列表。当(null? sequence)为真时,您想返回()。好吧,不,你也不能拥有它,因为它不是自我评估的;你必须引用它:'(). -
从列表中删除匹配或不匹配的项目是非常常见的操作。我会避免强迫程序员编写尴尬的否定,而只提供
keep-if和remove-if函数。
标签: scheme lisp racket predicate function-composition