3

Below is an attempt I've made to create a procedure that returns the function composition given a list of functions in scheme. I've reached an impasse; What I've written tried makes sense on paper but I don't see where I am going wrong, can anyone give some tips?

; (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
4

2 回答 2

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一些语法糖来表示更短的解决方案,以返回一个柯里化函数:

(define ((compose-all-rec fs) x)
  (foldr (λ (f a) (f a)) x fs))

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

((compose-all-rec (list abs inc)) -2)
=> 1
于 2013-01-22T20:47:13.720 回答
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)))))))
于 2013-01-23T14:29:36.167 回答