不使用 n 作为参数调用自身 n 次的递归函数
假设我有 myFunction($var)。它将操作 $var,在最终返回 $var 之前调用自身 3 次。有没有办法在不存储参数中调用次数的情况下执行此操作?
Suppose I have myFunction($var). It will manipulate $var, calling itself 3 times before finally returning $var. Is there a way to do this without storing the number of times it's been called in the parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
实现此目的的一种方法是使
n
可选,如果未定义,则默认为 3。我不知道 PHP 语法,但由于它被标记为与语言无关,所以这里是 javascript 等效项:One way of doing this is to make the
n
optional and defaults to 3 if not defined. I don't know the PHP syntax for this but since it's tagged language agnostic here's the javascript equivalent:我想到了两种相互竞争的方法:
Two competing methods off the top of my head:
您可以使用 static 语句设置一个 var 并在每次进入时检查其值(当然,每次进入时递增它,退出时递减)。
这是一篇有关基本概念的文章。
http://www.bellaonline.com/articles/art29070.asp
相关代码是
You could use the static statement to set a var and check its value each time you go in (incrementing it each time, of course, as you enter, decrementing as you exit).
Here's an article on the basic concept.
http://www.bellaonline.com/articles/art29070.asp
The relevant code is
您没有说明递归调用之后发生了什么,因此......
将
setrlimit(RLIMIT_STACK)
设置为一个小值和/或在其他调用中消耗足够的堆栈空间由于堆栈空间不足,myFunction()
在中止之前只能递归 3 次。You don't say what happens after the recursive calls, so…
setrlimit(RLIMIT_STACK)
to a small value and/or consume enough stack space in other calls thatmyFunction()
can only recurse 3 times before aborting due to lack of stack space.一些函数式语言支持这种构造。
例如,在 Mathematica 中,您可以定义:
其中 3 是 n 的默认值。
所以
Returns
和
Returns
当然你也可以定义
是否不需要调整递归调用的次数。
也许这更有趣。您还可以询问所有中间结果。
所以,如果你定义:
那么
Some functional languages support this kind of construct.
In Mathematica, for example you may define:
Where 3 is a default value for n.
So
Returns
and
Returns
Of course you may also define
if you don't need to adjust the number of recursive calls.
Perhaps this is more interesting. You may ask also for all the intermediate results.
So, if you define:
then
如果您知道您的函数将精确地调用自身三次,您调用它的时间为四次,那么最好创建一个更简单的非递归函数并使调用显式:
simpleF( simpleF(simpleF(simpleF($var))))
不太优雅,但更易于维护。
当然,这不会扩展到更大的数字。
If you know your function will call itself exacly three times, four with the time you called it, it is better to make a simpler, non-recursive function and make the calling explicit:
simpleF(simpleF(simpleF(simpleF($var))))
Less elegant, but more maintenable.
Of course, this wouldn't scale for a bigger number.