Scheme中的递归函数组合

时间:2013-01-22 20:14:04

标签: recursion functional-programming scheme 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

2 个答案:

答案 0 :(得分: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)))

请注意,最后需要返回一个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))

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

((compose-all-rec (list abs inc)) -2)
=> 1

答案 1 :(得分:0)

发布复选标记,但是到底是什么:

(define (compose-all fns)
  (assert (not (null? fns)))
  (let ((fn (car fns)))
    (if (null? (cdr fns))
        fn
        (let ((fnr (compose-all (cdr fns))))
          (lambda (x) (fn (fnr x)))))))