gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:55:49 25 4
gpt4 key购买 nike

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

有例子吗?

这个问题的开始只是如何打印递增的东西。第一个功能“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com