自动将循环重构为递归方法?

时间:2009-02-26 16:09:17

标签: java refactoring recursion loops

您是否知道一种工具可以自动将带有单个循环的方法重构为递归方法,最好是在Java中?

这是出于教学目的。

3 个答案:

答案 0 :(得分:4)

我不认为这样的工具存在,因为通常重构旨在提高性能,而不是降低它(使用递归方法而不是循环时就是这种情况)。如果是出于教学目的,为什么不让学生创造出能够做到这一点的工具呢?这样,他们就可以同时学习递归和解析。

我不知道递归是否可以自动化,但这里的转换应该是什么样子。为了演示,我们以伪代码的形式采用泛型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
    }
}

循环由四部分组成:initialization,初始化上下文(通常是变量); 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%确定这会在所有情况下都有效,但对于简单的循环,这应该是正确的。当然,这种转换可以很容易地适应其他类型的循环(同时,同时)。

答案 1 :(得分:2)

我并不完全确定这在一般意义上是可能的,因为在我看来,这似乎是the halting problem的变体。

答案 2 :(得分:0)

如果你是出于教学目的这样做的话,我认为你可以通过一组非常有限的案例来解决这个问题。那你可以写点什么吗

myMethod() {
  // startcode
  for (init,cond,incr) {
    // loopcode
  }
  //endcode
}

并将其转换为

myMethod() {
  //startcode
  init;
  recursive(value);
  //endcode
}
recursive(value) {
  if (!cond) {
    return
  } else {
    //loopcode
    incr;
    recursive(value);
}

我相信你可以为自己解决伪代码。

相关问题