std.range
Range (Range) iteration and adapters.
use std.rangeRange Literals
| Syntax | Meaning |
|---|---|
a..b | From a to b, with step 1 |
a..b..s | From a to b, with step s |
A range does not include its end value (closed on the left, open on the right). The step may be negative, indicating a descending range.
Iterator Protocol
iter returns a Result—a step of 0 takes the error path (E6009), so you must unwrap it or handle the error explicitly:
use std.assert
use std.range
use std.result
main: () -> Void = {
it = result.unwrap(range.iter(1..4))
assert(range.has_next(it))
}The two sides have opposite forms:
has_nexthas no&in its signature (src/std/range.rs:40) and consumes the iterator by value, so every check requires a freshiter;nexthas a&in its signature (src/std/range.rs:46) and borrows it.std.listis exactly the opposite—both of its methods borrow (&Iter(T)/&mut Iter(T)), so values can be fetched repeatedly from the same iterator. Copying the pattern from either side to the other will cause a mismatch.
use std.assert
use std.range
use std.result
main: () -> Void = {
// has_next has no &: create a new iterator for each check
a = result.unwrap(range.iter(1..3))
assert(range.has_next(a))
b = result.unwrap(range.iter(1..3))
assert(range.next(b) == 1)
}For everyday iteration, use for ... in directly:
use std.assert
main: () -> Void = {
nums = [1, 2, 3]
mut sum = 0
for x in nums {
sum = sum + x
}
assert(sum == 6)
}Function Overview
| Function | Signature |
|---|---|
iter | (r: Range(Int)) -> Result(Iterator(Any), Error) |
has_next | (it: Iterator(Any)) -> Bool |
next | (it: &Iterator(Any)) -> Any |
contains | (r: Range(Int), x: Int) -> Result(Bool, Error) |
abort_invalid_step | (r: Range(Int)) -> Any |
map | (it: Iterator(Any), f: (Any) -> Any) -> Iterator(Any) |
filter | (it: Iterator(Any), p: (Any) -> Bool) -> Iterator(Any) |
collect | (it: Iterator(Any)) -> Vec(Any) |
reduce | (it: Iterator(Any), init: Any, f: (Any, Any) -> Any) -> Any |
for_each | (it: Iterator(Any), f: (Any) -> Void) -> Void |
Iterator Protocol
iter
iter: (r: Range(Int)) -> Result(Iterator(Any), Error)Creates an iterator from a range.
r— the range, such as1..6or3..0..-1
Returns: Result.ok(iterator) on success; if the step is 0, returns Result.err with code set to E6009.
use std.assert
use std.range
use std.result
main: () -> Void = {
it = result.unwrap(range.iter(1..4))
assert(range.has_next(it))
}has_next
has_next: (it: Iterator(Any)) -> BoolWhether any unconsumed elements remain.
Consumes the iterator by value (the signature has no
&)—after a single check, the original iterator is invalid; calliteragain next time.
use std.assert
use std.range
use std.result
main: () -> Void = {
it = result.unwrap(range.iter(1..4))
assert(range.has_next(it))
}next
next: (it: &Iterator(Any)) -> AnyTakes the current element and advances the internal cursor by one position.
Returns: the current element; returns Void when iteration ends.
Borrows the iterator (the signature has
&,src/std/range.rs:46), so it does not consume it. This is the opposite ofhas_next, and also the opposite of the "both methods borrow" behavior on thestd.listside.
use std.assert
use std.range
use std.result
main: () -> Void = {
it = result.unwrap(range.iter(1..4))
assert(range.next(it) == 1)
}Descending ranges are supported as well:
use std.assert
use std.range
use std.result
main: () -> Void = {
desc = result.unwrap(range.iter(3..0..-1))
assert(range.next(desc) == 3)
}contains
contains: (r: Range(Int), x: Int) -> Result(Bool, Error)Determines whether x falls within the range.
r— the rangex— the value to test
Returns: Result.ok(Bool). The end value is exclusive (not included); when a step is specified, only elements aligned with the step match.
use std.assert
use std.range
use std.result
main: () -> Void = {
assert(result.unwrap(range.contains(1..10, 5)))
assert(!result.unwrap(range.contains(1..10, 10))) // End value excluded
assert(result.unwrap(range.contains(0..10..2, 4))) // Aligned with the step
assert(!result.unwrap(range.contains(0..10..2, 3))) // Not aligned
}abort_invalid_step
abort_invalid_step: (r: Range(Int)) -> AnyThe abort hook for an invalid step, called when for ... in consumes a range whose step is 0.
It always throws E6007 with the message Range step must be non-zero (for/in consumption). Normal code does not need to call it directly.
use std.range
main: () -> Void = {
// Using iter directly returns Err; this hook is not needed
r = range.iter(1..3)
}Adapters
map and filter return lazy adapters—they do not compute immediately. They produce results only after being consumed by collect / reduce / for_each / for ... in.
map
map: (it: Iterator(Any), f: (Any) -> Any) -> Iterator(Any)Applies f to each element and returns a new lazy iterator.
use std.assert
use std.list
use std.range
use std.result
main: () -> Void = {
doubled = range.collect(range.map(result.unwrap(range.iter(1..4)), x => x * 2))
assert(list.len(doubled) == 3)
assert(doubled[0] == 2)
}filter
filter: (it: Iterator(Any), p: (Any) -> Bool) -> Iterator(Any)Keeps elements for which p is true and returns a new lazy iterator.
use std.assert
use std.list
use std.range
use std.result
main: () -> Void = {
big = range.collect(range.filter(result.unwrap(range.iter(1..6)), x => x > 3))
assert(list.len(big) == 2)
assert(big[0] == 4)
}Adapters can be chained:
use std.assert
use std.list
use std.range
use std.result
main: () -> Void = {
r = 1..6
chained = range.collect(range.map(range.filter(result.unwrap(range.iter(r)), x => x % 2 == 0), x => x * 10))
// Value semantics: index reads consume `chained`, so bind each value to a local variable
first = chained[0]
second = chained[1]
assert(first == 20)
assert(second == 40)
}collect
collect: (it: Iterator(Any)) -> Vec(Any)Consumes the iterator and collects all elements into a List.
use std.assert
use std.list
use std.range
use std.result
main: () -> Void = {
xs = range.collect(result.unwrap(range.iter(1..4)))
assert(list.len(xs) == 3)
}reduce
reduce: (it: Iterator(Any), init: Any, f: (Any, Any) -> Any) -> AnyConsumes the iterator and folds it.
it— the iteratorinit— the initial accumulator valuef— the reduction function(accumulator, element) -> new accumulator
Note the parameter order differs from
std.list.reduce: this module uses(iterator, initial value, function), whilestd.listuses(list, function, initial value).
use std.assert
use std.range
use std.result
main: () -> Void = {
total = range.reduce(result.unwrap(range.iter(1..6)), 0, (acc, x) => acc + x)
assert(total == 15)
}for_each
for_each: (it: Iterator(Any), f: (Any) -> Void) -> VoidRuns f on each element for side effects.
use std.assert
use std.range
use std.result
main: () -> Void = {
// Prints 1, 2, 3
range.for_each(result.unwrap(range.iter(1..4)), x => println(x))
assert(true)
}Note that closures currently cannot capture and mutate an outer
mutvariable, so usingfor_eachfor accumulation does not work (it raisesE1001)—usereducefor accumulation.
Related
std.list— lists and their iteratorsstd.result— unwrap the return values ofiter/contains- Error code reference —
E6009invalid step
