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:
Notice that a single
lambdaneeds to be returned at the end, and it’s inside that lambda (which captures thexparameter and thefslist) that happens the actual application of all the functions – using theapply-allhelper procedure. Also notice that(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 of
foldrand a bit of syntactic sugar for returning a curried function:Either way the proposed solutions work as expected: