在 Scheme 中结合两个函数

Combining two functions in Scheme

我在自己的代码中完成了过滤功能和反向功能

(define reverse_
  (lambda (xs)
    (if (null? xs)
        xs
        (append (reverse_ (cdr xs))
                (list (car xs))))))

(define filter_
  (lambda (p? xs)
    (if (null? xs)
        xs
        (append (if (p? (car xs))
                    (list (car xs))
                    (list))
                (filter_ p? (cdr xs))))))

我想将这两个函数组合到 (reverse-filter) 函数中,即您可以键入 (reverse-filter symbol? '(1 2 3 a b c)),它会 return -> c b a.

现在只需输入 (reverse_ (filter_ symbol? '(1 2 3 a b c))) -> c b a 即可工作,但我只想将两者结合起来。

对于在一般情况下和在这个特定情况下执行此操作的任何帮助将不胜感激

对于一般情况,我们可以使用 curry and compose 过程(希望在您的解释器中可用),它们允许我们操纵其他过程:

((compose (curry filter_ symbol?) reverse_)
 '(1 2 3 a b c))
=> '(c b a)

出于说明目的,这里是两个过程的简单实现,以了解它们在幕后所做的事情:

(define (curry f x)
  (lambda (y) (f x y)))

(define (compose f g)
  (lambda (x) (f (g x))))

compose 是正确而懒惰的做法,但是由于列表是从头到尾迭代的,但是从尾到头创建的,因此一次完成时创建相反的结果实际上更有效:

(define (reverse-filter p? xs)
  (define (helper lst acc)
    (if (null? lst)
        acc
        (helper (cdr lst)
                (let ((a (car lst)))
                  (if (p? a)
                      (cons a acc)
                      acc)))))
  (helper xs '()))

(reverse-filter symbol? '(1 2 3 a b c))
; ==> (c b a)