简体   繁体   中英

Recursive Function Composition in Scheme

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

I'd try a different approach:

(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)))

Notice that a single lambda needs to be returned at the end, and it's inside that lambda (which captures the x parameter and the fs list) that happens the actual application of all the functions - using the apply-all helper procedure. Also notice that (apply fx) can be expressed more succinctly as (fx) .

If higher-order procedures are allowed, an even shorter solution can be expressed in terms of foldr and a bit of syntactic sugar for returning a curried function:

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

Either way the proposed solutions work as expected:

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

Post check-mark, but what the heck:

(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)))))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM