Automatically reorganize a loop into a recursive method?

Do you know a tool that automatically reorganizes a one-cycle method into a recursive method, preferably in Java?

It is intended for training.

+3
source share
3 answers

I don’t think that such a tool exists, since refactoring is usually aimed at increasing productivity, but not at reducing it (which is the case when using recursive methods instead of loops). If this is for educational purposes, why not get students to create a tool that would do this? Thus, they could learn at the same time as recursion and analysis.

, , . , , :

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% , , . , (while, do while).

+4

, , , .

+2

If you do this for training purposes, I think you can get away from it in a very limited number of cases. So you could just write something that took

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

and converted it to

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

I am sure you can sort the pseudo-code for yourself.

0
source

Source: https://habr.com/ru/post/1703907/


All Articles