0

I have a code block I would like to convert to a recursive block of code that doesn't use for or while loops. Suggestions?

sprite = function(dataset, pos){
  var size ={nrows : 3, ncolumns :3};
  var data = [];
  for(row = pos.row0; row < pos.row0+size.nrows; row++) {
    for(column = pos.column0; column < pos.column0+size.ncolumns; column++) {
      if(column == pos.column0) {
        data.push([dataset[row][column]]);
      } else {
        data[row].push(dataset[row][column]);
      }
    }  
  }
  return data;
}
6
  • 5
    is there a specific reason you'd rather use recursion? It will generally not save you any clock cycles, and it may be harder to understand/maintain. Commented Jul 2, 2012 at 14:08
  • 3
    Doesn't look like there is any benefit from doing that, the iterative version is going to be more readable and performant in this case Commented Jul 2, 2012 at 14:08
  • The reason that you would use recursion is if you've found something that is really effective and you want to magnify it. If you've done something ineffectively, or inefficiently, no matter how miniscule, recursion will multiply the inefficiency. Commented Jul 2, 2012 at 14:10
  • You may hide the for/while loops by using some collections utilities like the ones of jquery. But I'm not sure of the goal. Commented Jul 2, 2012 at 14:15
  • Recursion seems to be better for search based code... Commented Jul 2, 2012 at 14:31

1 Answer 1

3

The usual pattern is to convert a loop like

while(condition(x)){
    //do something
}

into

var go = function(x){
    if(condition(x)){
       //do something
       return go(nextValueOfX);
    }else{
       return finalReturnValue;
    }
}
go(0);

Basically, the loop condition becomes an if, iteration becomes an explicit recursive call and variables are either closed over or passed as arguments (depending on what is more convenient).


In your case it might look like

sprite = function(dataset, pos){
  var size ={nrows : 3, ncolumns :3};
  var data = [];
  var outerFor = function(row){
     if(row < pos.row0+size.nrows){
        var innerFor = ...;
        innerFor(0);
        outerFor(row+1);
     }
  }
  outerFor(0);
  return data;
}

Note that you would need to add some extra bells and whistles if you also want to convert this to continuation-passing-style for use with async code. I didn't explain that because I assume you are only doing this out of curiosity.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.