方案中的递归函数构成 [英] Recursive Function Composition in Scheme

查看:138
本文介绍了方案中的递归函数构成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我为创建一个程序返回给定函数列表中的函数组合的尝试。我陷入了僵局;我写的东西在纸上看起来很有意义,但是我没有看到我出错的地方,任何人都可以给出一些提示?

 ; (compose-all-rec fs) - >程序
; fs:listof过程
;返回fs中所有函数的函数组合:
;如果fs =(f0 f1 ... fN),结果为f0(f1(...(fN(x))...))
; (定义compose-all-rec(lambda(fs))
(if(empty?fs)empty
(lambda(fs)
(lambda(fs))
申请(第一个fs)(compose-all-rec(rest fs)))
))))

其中((compose-all-rec(list abs inc))-2)应该等于1


解决方案

我会尝试一种不同的方法:

 (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 fx)可以更简洁地表示为(fx)



如果允许更高阶的程序,更短的解决方案可以用 foldr 和一些语法糖用于返回咖喱功能:

 (define((compose-all-rec fs)x)
(foldr(λ(fa)(fa))x fs))

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

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


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

这篇关于方案中的递归函数构成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆