[英]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. 请注意,最后需要返回一个lambda
,并且它位于lambda(捕获x
参数和fs
列表)内部,该lambda发生在所有函数的实际应用中 - 使用apply-all
帮助程序。 Also notice that (apply fx)
can be expressed more succinctly as (fx)
. 还要注意(apply fx)
可以更简洁地表达为(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: 如果允许更高阶的程序,则可以用foldr
和一些语法糖来表示更短的解决方案,以便返回一个curried函数:
(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)))))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.