Texas Instruments TI89 Developer Guide - Page 221
resulting new list is in reverse order. Another loop can be added simply
UPC - 033317198566
View all Texas Instruments TI89 manuals
Add to My Manuals
Save this manual to your list of manuals |
Page 221 highlights
Chapter 15: Expressions and The Expression Stack 179 This function illustrates three key elements of a process that loops over the elements of a list. • Decrement the index to move it from the LIST_TAG to the first list element. • Test for END_TAG at the current location to determine when to stop. • Use next_expression_index to advance the index through the elements of the tail. Here is another example that illustrates this pattern - a possible implementation of push_sumlist. void push_sumlist (EStackIndex i) { push0 (); /* push a zero on the estack */ --i; /* move index to first element of list */ while (END_TAG != ESTACK(i)) /* while not at end of list */ { add_to_top (i); /* add current element to sum */ i = next_expression_index (i); /* step to next element */ } } Note that the three key elements are identical. The differences from the previous example are in the initialization (push0), the operation (add_to_top), and the completion (return value on the estack). Looping is less applicable to procedures that create a new copy of a list. No two elements of a list are necessarily the same size. A computed result is not necessarily the same size as the corresponding input value. Therefore, overwriting each element of a list with a newly computed element is not a reasonable approach. Also looping operates on the list from the first element (highest on the stack) down to the last element (lowest on the stack). If the operation of the loop is to push a computed value based on each element, the resulting new list is in reverse order. Another loop can be added simply to reverse the order of the elements. However, this approach requires the additional stack space to make another copy of the list and requires the additional time to make the correctly ordered copy, and finally, delete the incorrectly ordered copy. An alternative implementation for routines that make new copies of lists is to use recursion. The following example represents a pattern that occurs frequently. The key elements are: • A main routine that calls a subroutine to operate on the tail of the list and then pushes a LIST_TAG on top of the resulting tail to form the new list. • A subroutine that recurs down to the END_TAG of the tail doing nothing on the way and then pushes each newly computed value on the way out of the recursion giving the resulting list in correct order. TI-89 / TI-92 Plus Developer Guide Not for Distribution Beta Version January 26, 2001