【问题标题】:Scheme, recursion with constant value方案,具有恒定值的递归
【发布时间】:2014-05-25 12:15:35
【问题描述】:

我之前问过letrec和尾递归, 我从答案中对 letrec 和尾递归有了更好的理解 我的最终目标是,通过这些,实现方程式的方案代码: 例如y(i) = x(i) + 2 ,其中 x(i), y(i) 是列表,因此这些将与 i 尾递归。 现在 x, y, i 将在尾递归例程中,因此这部分代码将是: 但是 5 总是相同的(不是递归的),但是你可以选择这个常数作为输入参数,比如说“常数”

如此预期的输出,例如当你尝试这个时:(equationFunc 0 3 1 (lambda (x) x) 5)

它应该像这样工作...((0 1 2) (0+5 1+5 2+5))

最终预期输出:((0 1 2) (5 6 7))

因为它会计算方程 y(i) = x(i) + 5(i 边界从 0 到 2 - 所以 x(i) , y(i) 必须是递归的)但不是 "+ 5 ”。我只是想不出如何处理函数实现尾递归例程中的“+5”。

我认为这样的代码..但是是的,它不起作用...

(define equationFunc
 (lambda (start end res func constant)
  (letrec (helper
         (lambda (x i y constant)
           (if (>= i start)
               (helper (cons i (+ x constant))
                       (- i res)
                       (cons (func i) y)
                       0)
               (cons x (cons y '()))
            )              
          )
         )
   (helper '() end '() 0)          
  )))

谁能给点建议?

【问题讨论】:

  • 这个问题一点都不清楚。 func 应该做什么? equationFunc 中的az 的用途是什么?因为您没有在帮助程序中使用它们。如果我用这些参数调用函数:(equationFunc 0 3 1 identity 5) 你期望的输出是什么?
  • “输出”我的意思是:在评估过程后解释器将打印什么,不要试图用语言解释结果,写准确预期的结果,因为它会打印在屏幕上。
  • 我编辑了这个问题,希望更清楚我想做什么

标签: scheme tail-recursion


【解决方案1】:

不清楚应该如何构建“方程式”。我的最佳猜测是:

(define equationFunc
  (lambda (start end res func constant)
    (letrec ((helper
              (lambda (x i y)
                (if (>= i start)
                    (helper (cons i x)
                            (- i res)
                            (cons (+ (func i) constant) y))
                    (list x y)))))
      (helper '() (- end 1) '()))))

请注意,我们不必传递 startendresfuncconstant 作为 helper 过程的参数,我们只需要传递保持在每次迭代中发生变化,即:xyi。它适用于问题中显示的示例输入/输出:

(equationFunc 0 3 1 (lambda (x) x) 5)
=> '((0 1 2) (5 6 7))

【讨论】:

  • @user1915570 如果这个答案有帮助,请不要忘记点击左侧的复选标记accept ;)
猜你喜欢
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
相关资源
最近更新 更多