// This method returns a picture with p arranged in numberItems // equally spaced columns (ie a row with numberItems elements). public Picture row (Picture p, int numberItems) { if (numberItems<=0) { // base case: a row with no elements is empty return empty(); } else { // general case: a row is a picture with a row of one // fewer number of elements to its right return beside(p, row(p, numberItems-1), 1.0/numberItems); } }To create an iterative version, we need to eliminate the pending operation above which is the beside that is left to do once the recursive call finishes. In order to do that, we will need to introduce a new state variable which will hold our partial results at each step of the iteration. For this particular problem, the following state table can be derived for the execution of
row(patch(Color.red),4)
numberItems | numberDone | p | new_p |
---|---|---|---|
4 | 0 | ||
4 | 1 | ||
4 | 2 | ||
4 | 3 | ||
4 | 4 |
beside(p,new_p,1.0/(numberDone+1))
// iterative (tail-recursive) version of row public Picture rowIter (Picture p, int numberItems) { return rowTail(numberItems,0,p,empty()); } public Picture rowTail (int numberItems, int numberDone, Picture p, Picture new_p) { if (numberDone==numberItems) { // we're finished return new_p; } else { // create next row of state table return rowTail(numberItems, numberDone+1, p, beside(p,new_p,1.0/(numberDone+1))); } } // while loop version of row public Picture rowWhile (Picture p, int numberItems) { Picture new_p = empty(); // initialize state variable int numberDone = 0; // initialize counter while (numberDone<numberItems) { // continuation condition new_p = beside(p,new_p,1.0/(numberDone+1)); // update new_p numberDone = numberDone + 1; // update counter } return new_p; // we're done so return our picture } // for loop version of row public Picture rowFor (Picture p, int numberItems) { Picture new_p = empty(); // initialize state variable for (int numberDone=0; numberDone<numberItems; numberDone=numberDone+1) { new_p = beside(p,new_p,1.0/(numberDone+1)); } return new_p; // we're done so return our picture }
Notice the similarity between the while and for loop versions above. A for loop is just syntactic sugar (an easier way of writing) for a while loop. The blue bold lines in the while loop get placed all on one line in the for loop.