【问题标题】:Recursive Function Composition in SchemeScheme中的递归函数组合
【发布时间】:2013-01-06 04:38:53
【问题描述】:

下面是我尝试创建一个过程,该过程返回给定方案中的函数列表的函数组合。我陷入了僵局;我写的东西在纸上是有道理的,但我看不出哪里出错了,谁能给点建议?

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

【问题讨论】:

  • 您是否了解过用于解决此类问题的设计方法或其他正式方法?请参阅:ccs.neu.edu/home/matthias/HtDP2e/index.html 例如,您可能想要考虑一些具体的测试用例。具体来说,在给定一些简单输入的情况下表达预期输出。您已经直接进入编码领域,而对于比单行代码更大的问题,这通常是一种有问题的方法。
  • 空箱的具体例子:(compose-all-rec (list))应该是什么?你期望((compose-all-rect (list)) -2) 是什么?

标签: recursion functional-programming scheme racket


【解决方案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 f x) 可以更简洁地表示为(f x)

如果允许高阶过程,则可以用foldr 和返回curried 函数的一些语法糖来表示更短的解决方案:

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

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

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

【讨论】:

  • 我怎样才能改变它以获得 fN(fN-1(...(f0(x))...)) ?
  • @user2075220 反转输入列表
  • 我可以在函数内部做这个吗?
  • @user2075220 你为什么不试试呢?你可以自己检查。
  • 好的,谢谢,我不知道在哪里放置反向但我已经知道了
【解决方案2】:

张贴复选标记,但到底是什么:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多