Overview
The tilde operator ~ defines ranges in Linea v4.1. It's used primarily in for loops for clean, readable iteration.
Basic Syntax
start~end
start~end step increment
Inclusive Ranges
The ~ operator creates inclusive ranges (both endpoints included):
Simple Range
for i from 1~5 {
display i
}
// Output: 1, 2, 3, 4, 5
Range from 0
for i from 0~10 {
display i
}
// Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Step Values
Positive Step (Skip Forward)
for i from 0~20 step 5 {
display i
}
// Output: 0, 5, 10, 15, 20
Negative Step (Backward)
for i from 10~1 step -1 {
display i
}
// Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
Large Steps
for i from 0~100 step 10 {
display i
}
// Output: 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
Dynamic Ranges
Use variables for start and end points:
var start @ int = 5
var end @ int = 15
for i from start~end {
display i
}
Array Iteration
Using Array Length
var arr @ [int] = [10, 20, 30, 40]
var n @ int = len(arr)
for i from 0~(n-1) {
display arr[i]
}
Reverse Array Iteration
var arr @ [int] = [1, 2, 3, 4]
for i from 3~0 step -1 {
display arr[i]
}
// Output: 4, 3, 2, 1
Common Patterns
Fibonacci Sequence
var a @ int = 0
var b @ int = 1
for i from 0~9 {
display a
var temp @ int = a + b
a = b
b = temp
}
Times Table
var n @ int = 5
for i from 1~10 {
display n * i
}
Differences from Other Languages
| Language | Syntax | Notes |
|---|---|---|
| Python | range(1, 11) |
Exclusive end |
| Rust | 1..=10 |
Inclusive |
| Linea | 1~10 |
Inclusive, clean |
💡 Note: Linea's range operator is inclusive on both ends, making it intuitive for humans (1~10 really means 1 to 10).
Performance Considerations
- Ranges are compiled efficiently: No runtime overhead
- Positive steps: Compiled to Rust's optimized ranges
- Negative steps: Use while loops internally
- Cache locality: Better performance with sequential access