Up: Formatting Transformation Functions
Previous: Recursive substitution.

#### Example 10. Constructing a polynomial expression.

The following constructs an expression representing a polynomial in with an arbitrary number of numerical coefficients:

```*  Declare variables.
INTEGER NCOEFF, STATUS, I, NSUBS
REAL COEFF( NCOEFF )
CHARACTER * ( * ) EXPRS

*  Initialise the expression.
EXPRS = '<next_term><coeff>'                     [1]

*  Substitute each coefficient value.
DO 1 I = 1, NCOEFF
CALL TRN_STOKR( 'coeff', COEFF( I ), EXPRS,   [2]
:                   NSUBS, STATUS )

*  Expand the token representing the next term.
IF( I .NE. NCOEFF ) THEN
CALL TRN_STOK( 'next_term',                [3]
:                     '(<next_term><coeff>)*X+',
:                     EXPRS, NSUBS, STATUS )

*  Eliminate the final '<next_term>' token.
ELSE
CALL TRN_STOK( 'next_term', ' ',           [4]
:                     EXPRS, NSUBS, STATUS )
ENDIF
1  CONTINUE
```

Programming notes:

1. The character variable EXPRS, which is to contain the expression, is initialised to the value ``<next_term><coeff>`'.

2. The ``<coeff>`' token is substituted with a coefficient value (say 0.1) to give ``<next_term>0.1`'.

3. The ``<next_term>`' token is expanded to give ``(<next_term><coeff>)*X+0.1`'. The process is then repeated to replace the ``<next_term><coeff>`' part of this expression using the value of the next coefficient.

4. After the last coefficient value has been substituted the remaining ``<next_term>`' token is eliminated by replacing it with a blank string.

The effect of this algorithm with (say) the 5 polynomial coefficients 0.1, 0.12, 1.06, 4.4 & 1E7, would be to produce the following expression:

```'((((1E-7)*X+(-4.4))*X+1.06)*X+0.12)*X+0.1'
```

which casts the polynomial into a form for efficient evaluation using Horner's method.