使用单个foldr调用编写过滤器?

时间:2016-02-19 21:58:17

标签: filter scheme racket fold

目标是编写过滤函数,只有一个折叠调用,没有递归或任何其他更高阶的过程(map,andmap,apply等)。

目前我正在使用

  (define (filter ps xs)
    (if (empty? xs)
        ps
        (foldr (lambda (p y)
                 (if (andmap p xs)
                     (cons p y)
                     y))
               '()
               ps)))

然而它使用andmap函数,这被认为是一个更高阶的过程

目标是

(filter positive? '(-1 2 3 4 -5 -6)) 
=> '(2 3 4)

单次调用foldr

2 个答案:

答案 0 :(得分:3)

我认为您误解了http://<public IP>的工作方式,您必须将列表作为最后一个参数进行处理,并且要实现过滤器,请对每个元素应用foldr想测试。最好尝试这样的事情:

ps

按预期工作:

(define (filter ps xs)
  (foldr (lambda (p y)
           (if (ps p)
               (cons p y)
               y))
         '()
         xs))

答案 1 :(得分:0)

这听起来像是家庭作业。我可以看到为什么foldr被选中,但是为了看到它在foldl实现,你去了

(define (filter f xs)
  (reverse (foldl (λ (x ys) (if (f x) (cons x ys) ys))
                  null
                  xs)))

(filter positive? '(-1 2 3 4 -5 -6)) 
;=> '(2 3 4)

foldl具有明显优于foldr的优势,因为它是通过适当的尾调用实现的。

相关问题