Implementing an iterator function with a C user-defined function
To implement an iterator function with a C user-defined function:
0, 1, 1, 2, 3, 5, 8, 13
typedef struct fibState1 /* function-state structure */
{
mi_integer fib_prec1; /* second most recent number in series */
mi_integer fib_prec2; /* most recent number in series */
mi_integer fib_ncomputed; /* number computed */
mi_integer fib_endval; /* stop value */
}fibState;
/* fibGen(): an iterator function to return the Fibonacci series.
* This function takes a stop value as a parameter and returns the
* Fibonacci series up to this stop value.
*
* Three states of iterator status:
* SET_INIT : Allocate the defined user-state structure.
* SET_RETONE : Compute the next number in the series.
* SET_END : Free the user-allocated user-state structure.
*/
mi_integer fibgen(stop_val,fparam)
mi_integer stop_val;
MI_FPARAM *fparam;
{
mi_integer next;
fibState *fibstate = NULL;
switch( mi_fp_request(fparam) )
{
case SET_INIT:
next = fibGen_init(stop_val, fparam);
break;
case SET_RETONE:
next = fibGen_retone(fparam);
fibstate = (fibState *)mi_fp_funcstate(fparam);
if ( next > fibstate->fib_endval )
{
mi_fp_setisdone(fparam, 1);
next = 0; /* return value ignored */
}
break;
case SET_END:
next = fibGen_end(fparam);
break;
}
return (next);
}
- Once, to initialize the calculation of the Fibonacci series of
numbers.
At this point, the database server has set the iterator status to SET_INIT and fibGen() calls the fibGen_init() function (see Figure 1).
- Repeatedly, to calculate each number in the series until a number
exceeds the stop value.
As long as the number is less than the stop value, the database server sets the iterator status to SET_RETONE and fibGen() calls the fibGen_retone() function (see Figure 1).
- Once, to deallocate resources that the iterator function uses.
At this point, the database server has set the iterator status to SET_END and fibGen() calls the fibGen_end() function (see Figure 1).
- If this number is greater than the user-specified stop value (in
the fib_endval field of the user-state information), the end
condition was reached.
The fibGen() function calls the mi_fp_setisdone() function to set the iterator-completion flag to 1. The function then exits with a return value of zero. However, this last return value of 0 is not returned as part of the active set. The database server calls the next iteration of fibGen() with an iterator-status value of SET_END.
- If the next Fibonacci number is less than or equal to the stop
value, the end condition was not reached.
The function returns this next number in the Fibonacci series to the active set. The database server calls the next iteration of fibGen() with an iterator-status value of SET_RETONE.