您是否知道一种工具可以自动将带有单个循环的方法重构为递归方法,最好是在Java中?
这是出于教学目的.
解决方法:
我不认为这样的工具存在,因为通常重构旨在提高性能,而不是降低它(使用递归方法而不是循环时就是这种情况).如果是出于教学目的,为什么不让学生创造出能够做到这一点的工具呢?这样,他们可以同时学习递归和解析.
我不知道递归是否可以自动化,但这里的转换应该是什么样子.为了演示,我们在伪代码中采用泛型for循环:
loopFunc() // method (could return a value or not)
{
for (initialization ; // Sets the context
test ; // Test continuation wrt the context
counting_exp // Update the context after each iteration
)
{
loop_body
}
}
循环由四部分组成:初始化,初始化上下文(通常是变量); test,这是一个布尔表达式,用于检查循环是否完成; counting_exp,是每次迭代后执行的语句;最后,loop_body,表示在每次迭代时执行的操作.
这个方法的递归版本应该分为两部分:一部分用于初始化,另一部分用于实际执行循环:
recFunc()
{
initialization // Sets the context
innerRecFunc(context) // We need to pass the context to the inner function
}
innerRecFunc(context)
{
if not test then return // could return a value
else
{
loop_body // Can update context
counting_exp // Can update context
innerRecFunc(context) // Recursive call (note tail-recursion)
}
}
我没有想到这个问题足以100%确定这在所有情况下都能正常工作,但对于简单的循环,这应该是正确的.当然,这种转换可以很容易地适应其他类型的循环(同时,同时).
标签:java,recursion,loops,refactoring
来源: https://codeday.me/bug/20190827/1743836.html