方案过滤功能

时间:2016-10-27 00:29:40

标签: filter scheme filtering

到目前为止,我已经将两个函数应用于列表中。我试图让函数只返回操作适用的元素,例如所有奇数。我只返回一个布尔值,表示每个数字是否为奇数。

(define (accumulate op initial sequence)
   (if (null? sequence)
       initial
       (op (car sequence)
           (accumulate op initial (cdr sequence)))))

(define (my-filter predicate sequence)
    (accumulate (lambda (element rest)(cons (predicate element) rest)) '()      sequence))



(my-filter odd? (list 1 2 3 4 5 6 7))

1 个答案:

答案 0 :(得分:1)

您只需在条件表达式中使用predicate即可。如果谓词的计算结果为#t,则将当前元素添加到答案中,否则将其跳过:

(define (my-filter predicate sequence)
  (accumulate (lambda (element rest)
                (if (predicate element)
                    (cons element rest)
                    rest))
              '()
              sequence))

例如:

(my-filter odd? (list 1 2 3 4 5 6 7))
=> '(1 3 5 7)