Scheme中的递归函数组合

3 recursion scheme functional-programming racket

下面是我尝试创建一个过程,该过程返回给定方案中的函数列表的函数组合.我陷入了僵局; 我写的文章在纸上有意义但我不知道我哪里出错了,有人可以提供一些建议吗?

; (compose-all-rec fs) -> procedure 
; fs: listof procedure
; return the function composition of all functions in fs:
; if fs = (f0 f1 ... fN), the result is f0(f1(...(fN(x))...))
; implement this procedure recursively

(define compose-all-rec (lambda (fs)
     (if (empty? fs) empty
     (lambda (fs)
         (apply (first fs) (compose-all-rec (rest fs)))
     ))))

where ((compose-all-rec (list abs inc)) -2) should equal 1
Run Code Online (Sandbox Code Playgroud)

Ósc*_*pez 5

我尝试了另一种方法:

(define (compose-all-rec fs)
  (define (apply-all fs x)
    (if (empty? fs)
        x
        ((first fs) (apply-all (rest fs) x))))
  (? (x) (apply-all fs x)))
Run Code Online (Sandbox Code Playgroud)

请注意,最后lambda需要返回一个,并且它位于lambda(捕获x参数和fs列表)内部,它发生了所有函数的实际应用 - 使用apply-all帮助程序.另请注意,(apply f x)可以更简洁地表达为(f x).

如果允许更高阶的程序,则可以用一个更简单的解决方案来表达,foldr以及一些用于返回curried函数的语法糖:

(define ((compose-all-rec fs) x)
  (foldr (? (f a) (f a)) x fs))
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,建议的解决方案都按预期工作

((compose-all-rec (list abs inc)) -2)
=> 1
Run Code Online (Sandbox Code Playgroud)