Programming Languages - Ranges
C++
Since C++20.
- Ranges = iterable sequences. An abstraction. Requires
begin()
andend()
.- Containers = ranges owning their elements. E.g.
std::vector
- Views = lightweight objects that indirectly represent ranges. View do not own the underlying data.
- Containers = ranges owning their elements. E.g.
Go
The range
form of the for
loop iterates over a slice or map.
When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.
for i, v := range []int{1, 2, 4, 8, 16, 32, 64, 128} {
fmt.Printf("%d, %d\n", i, v)
}
// This returns the index, NOT the value:
for i := range pow {
// ...
}
// The right way to get values:
for _, value := range pow {
// ...
}
JavaScript
No built-in ranges, but can use array index to get a sequence:
> Array.from(new Array(5), (x, i) => i)
[0, 1, 2, 3, 4]
Python
In Python, range()
is a function to create a sequence.
Syntax: range(start, stop, step)
.
start
: optional, default 0.stop
: required, exclusive.step
: optional, default 1.
>>> [n for n in range(1, 10, 2)]
[1, 3, 5, 7, 9]
Kotlin
for (i in 1..10) print(i) // inclusive
for (i in 1 until 10) print(i) // exclusive
for (i in 1..10 step 2) print(i)
for (i in 10 downTo 1) print(i)
Rust
1..2; // std::ops::Range
3..; // std::ops::RangeFrom
..4; // std::ops::RangeTo
..; // std::ops::RangeFull
5..=6; // std::ops::RangeInclusive
..=7; // std::ops::RangeToInclusive
Shell
Generate sequence
$ seq 5856 5859
5856
5857
5858
5859
Set delimiter by -s
('\n'
As default)
$ seq -s ',' 5856 5859
5856,5857,5858,5859,