Evaluation in Iteration Functions

The built-in Wolfram Language iteration functions such as (RefLink[Table, paclet:ref/Table]) and (RefLink[Sum, paclet:ref/Sum]) evaluate their arguments in a slightly special way.

When evaluating an expression like (RefLink[Table, paclet:ref/Table])[f,{i,(Subscript[i, max])}], the first step, as discussed in "Blocks and Local Values", is to make the value of i local. Next, the limit (Subscript[i, max]) in the iterator specification is evaluated. The expression f is maintained in an unevaluated form, but is repeatedly evaluated as a succession of values are assigned to i. When this is finished, the global value of i is restored.

The function (RefLink[RandomReal, paclet:ref/RandomReal])[] is evaluated four separate times here, so four different pseudorandom numbers are generated:

Table[RandomReal[],{4}]

This evaluates (RefLink[RandomReal, paclet:ref/RandomReal])[] before feeding it to (RefLink[Table, paclet:ref/Table]). The result is a list of four identical numbers:

Table[Evaluate[RandomReal[]],{4}]

In most cases, it is convenient for the function f in an expression like (RefLink[Table, paclet:ref/Table])[f,{i,(Subscript[i, max])}] to be maintained in an unevaluated form until specific values have been assigned to i. This is true in particular if a complete symbolic form for f valid for any i cannot be found.

This defines fac to give the factorial when it has an integer argument, and to give NaN (standing for "Not a Number") otherwise:

fac[n_Integer]:=n!;fac[x_]:=NaN

In this form, fac[i] is not evaluated until an explicit integer value has been assigned to i:

Table[fac[i],{i,5}]

Using (RefLink[Evaluate, paclet:ref/Evaluate]) forces fac[i] to be evaluated with i left as a symbolic object:

Table[Evaluate[fac[i]],{i,5}]

In cases where a complete symbolic form for f with arbitrary i in expressions such as (RefLink[Table, paclet:ref/Table])[f,{i,(Subscript[i, max])}] can be found, it is often more efficient to compute this form first, and then feed it to (RefLink[Table, paclet:ref/Table]). You can do this using (RefLink[Table, paclet:ref/Table])[(RefLink[Evaluate, paclet:ref/Evaluate])[f],{i,(Subscript[i, max])}].

The (RefLink[Sum, paclet:ref/Sum]) in this case is evaluated separately for each value of i:

Table[Sum[i^k,{k,4}],{i,8}]

It is however possible to get a symbolic formula for the sum, valid for any value of i:

Sum[i^k,{k,4}]

By inserting (RefLink[Evaluate, paclet:ref/Evaluate]), you tell the Wolfram Language first to evaluate the sum symbolically, then to iterate over i:

Table[Evaluate[Sum[i^k,{k,4}]],{i,8}]

Evaluation in iteration functions.