recursion - 为什么在递归函数中向上计数总是需要两个参数?

标签 recursion scheme lisp

我用递归和循环宏编写了一些简单的循环,但令我困扰的是向上计数需要两个参数而向下计数不需要。

有例子吗?

这个问题的开始只是如何打印递增的东西。第一个功能“printsomestuff”是我开始的地方。

(defun printsomestuff (stuff times) 
  (if (= times 0)
      'im-the-return-value
      (progn 
        (print stuff)
        (printsomestuff stuff (1- times)))))

(defun counting-down (topnumber)
  (if (= topnumber 0)
      'done
      (progn 
        (print topnumber)
        (counting (- topnumber 1)))))


(defun loopcounting (uptonumber)
  (loop for i from 1 to uptonumber
    do (print i)))

(defun recurcounting-up (uptonumber)
  (let ((incrementer 0))
    (if  
     (= incrementer uptonumber)
     'done
     (progn 
       (print incrementer)
       (recurcounting-up (+ incrementer 1))))))

(defun recur-counting-up-two (uptonumber startnumber)
  (if (> startnumber uptonumber)
      'done
      (progn
        (print startnumber)
        (recur-counting-up-two uptonumber (+ startnumber 1)))))

recurcounting-up 以 0 无限循环,因为在每次函数调用时都会重置增量器。这不是我想要的。

最佳答案

这与你是向上数还是向下数无关。问题是递归的基本情况是可以在函数中硬编码还是需要作为参数提供。在您的倒计时示例中,您总是以 0 结束,因此它不需要是一个参数——您只需要一个当前数字的参数。但是在您的计数示例中,结束数字不能放入代码中,因此它需要将其作为第二个参数。

如果您总是数到 100,则可以像倒数示例一样编写代码。同样,如果您想倒数到任意数字,而不仅仅是 0,您将需要两个参数。

关于recursion - 为什么在递归函数中向上计数总是需要两个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300332/

相关文章:

javascript - 两个函数之间的递归调用

scheme - SICP 练习 1.16 - 我的解决方案正确吗?

scheme - 如何使用 with-type 在非类型化模块中使用类型化 Racket 片段?

lisp - 在 Elisp 中如何将参数传递给函数?

python - python中的三向字典深度合并

python - 子集总和为 `itertools.combinations`

sql - 使用递归 CTE 遍历父/子树?

scheme - 花括号 {} 替换 Racket 中的 'begin'

recursion - 在 lisp 代码中修复这个未定义的函数?

scheme - 在 Racket 中的宏扩展期间评估表单