1. for
Executes a procedure repeatedly with a numeric control variable.
1.2. Stack Effects
| Level | Object |
|---|---|
3 |
|
2 |
|
1 |
|
0 |
|
| Level | Object |
|---|---|
(varies) |
Results from procedure executions |
1.3. Description
for executes proc repeatedly, passing it a sequence of values from initial by steps of increment to limit.
The operator maintains an internal control variable: 1. Sets control variable to initial 2. Before each iteration: compares with limit 3. If not exceeded: pushes control variable, executes proc, adds increment 4. Repeats until termination condition met
Termination: * If increment > 0: stops when control variable > limit * If increment < 0: stops when control variable < limit * If initial meets condition: proc never executes
1.5. Examples
1 1 5 { = } for
% Prints: 1 2 3 4 5
0 % Accumulator
1 1 4 { add } for
% Result: 10 (sum of 1+2+3+4)
3 -.5 1 { = } for
% Prints: 3.0 2.5 2.0 1.5 1.0
5 array
0 1 4 {
2 copy exch dup 10 mul put
} for
% Result: [0 10 20 30 40]
1.6. Common Use Cases
1.7. Common Pitfalls
| Real Number Precision - Using reals for control values can cause precision errors. |
0 0.1 1 { } for % May not reach exactly 1.0
% Use integers when possible
| Stack Accumulation - If proc doesn’t consume the control variable, values accumulate. |
1 1 5 { } for
% Stack: 1 2 3 4 5 (all values left!)
| Increment Sign Matters - Positive increment counts up, negative counts down. |
5 1 1 { } for % Never executes (5 > 1 already)
5 -1 1 { } for % Executes: 5, 4, 3, 2, 1
Early Exit - Use exit to terminate loop early.
|
1.8. Error Conditions
| Error | Condition |
|---|---|
[ |
Too many iterations or proc pushes too much |
[ |
Fewer than 4 operands on stack |
[ |
Wrong operand types |
1.9. Implementation Notes
-
Control variable is internal (not on stack)
-
Very efficient for numeric sequences
-
Works with both integers and reals
-
Termination tested before each iteration