Composition of recursive functions in a schema

Below I tried to create a procedure that returns the composition of a function given by a list of functions in a schema. I am at a dead end; What I've written makes sense on paper, but I can't see where I am going wrong, can anyone provide some advice?

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

      

+3


source to share


2 answers


I would 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)))

      

Note that a single must be returned at the end lambda

, and inside a lambda (which captures the parameter x

and the list fs

) that does the actual application of all functions - using a apply-all

helper procedure. Also note that it (apply f x)

can be expressed more succinctly as (f x)

.

If higher-order procedures are allowed, an even shorter solution can be expressed in terms foldr

and a little syntactic sugar for returning the curried function :



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

      

In any case, the proposed solutions work as expected:

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

      

+5


source


Check the box, but what the hell:



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

      

0


source







All Articles