Texas Instruments TI89 Developer Guide - Page 222
routine makes it unnecessary to write the recursive subroutine
UPC - 033317198566
View all Texas Instruments TI89 manuals
Add to My Manuals
Save this manual to your list of manuals |
Page 222 highlights
180 Chapter 15: Expressions and The Expression Stack Here is a pair of functions that combine to compute the square root of each element of a list. void push_sqrt_list (EStackIndex i) { /* i indexes a list */ push_sqrt_tail (i - 1u); /* compute the sqrt of the tail */ push_quantum (LIST_TAG); /* push a LIST_TAG on top */ } void push_sqrt_tail (EStackIndex i) { /* i indexes a tail. Pushes a tail of the square roots of the elements. */ if (END_TAG == ESTACK (i)) /* if at the bottom of the tail */ push_quantum (END_TAG); /* push bottom of new tail */ else { /* recur to next element of tail */ push_sqrt_tail (next_expression_index (i)); /* on the way out, compute sqrt of each element */ push_sqrt (i); } } The recursive alternative has the advantage of automatically creating the new list in the correct order. The disadvantage is that recursion consumes more hardware stack for the recursive stack frames. This approach makes a recursive subroutine call, thereby using a stack frame for each element of the list, and finally, the END_TAG that terminates the list. The recursive pattern for computing a list result from a list input is so common that the system includes a generalized procedure that provides the recursion. The map_tail routine makes it unnecessary to write the recursive subroutine as shown in the previous example. The first argument in map_tail is a pointer to a function that pushes a single result value based on a single input value. Its second argument is a tail of input values. It performs the recursion, applying the specified function to each element of the tail. Thus, push_sqrt_list can be implemented as follows, making push_sqrt_tail unnecessary. void push_sqrt_list (EStackIndex i) { /* apply sqrt function to the tail */ map_tail (push_sqrt, i - 1u); /* push the LIST_TAG on top of the tail */ push_quantum (LIST_TAG); } TI-89 / TI-92 Plus Developer Guide Not for Distribution Beta Version January 26, 2001