std/ranges
Import with import std/ranges.
Exports
Section titled “Exports”Types
struct Range
Section titled “struct Range”struct Range<T> where T: Comparable
opaque — construction surface is private to its defining module
Comparable Range. Bounded range literals desugar to this single struct:
1..5, "a".."z", and 0.0..=1.0 carry their start/end values and whether
the end is inclusive. end is None only for integer ranges built via
Range.from(N) or Range.naturals(); in that case inclusive carries no
meaning and is canonically False.
Range<T> impls Iter<T> when T also impls Discrete. Generic
ranges over non-discrete comparable values are still useful as
containment/interval values.
Range.from
Section titled “Range.from”fn from(n: Int): Range<Int>
type function on Range
Returns an unbounded ascending integer range starting at n.
Pair with Iter.take(N) before materializing.
Interactive Tests
assert Range.contains?(Range.from(1), 100)
refute Range.bounded?(Range.from(1))
Range.naturals
Section titled “Range.naturals”fn naturals(): Range<Int>
type function on Range
Returns an unbounded ascending integer range starting at 0.
Pair with Iter.take(N) before materializing.
Interactive Tests
assert Range.contains?(Range.naturals(), 0)
refute Range.contains?(Range.naturals(), -1)
Range.step_by
Section titled “Range.step_by”fn step_by<T, S>(r: Range<T>, by: S): Iter<T> where T: Comparable and Steppable<S>
type function on Range
Returns a lazy iterable that advances through the range by by.
Plain ranges are iterable only when their endpoint type is Discrete;
step_by is for domains where the caller supplies the step. Decimal
steps are exact. For example, Range<Int> can step by Int, while a
custom calendar type can step by Days when it implements
Steppable<Days>.
Interactive Tests
assert 1.0d..=1.3d
|> Range.step_by(0.1d)
|> Iter.to_list()
|> List.equal?([1.0d, 1.1d, 1.2d, 1.3d])
Range.contains?
Section titled “Range.contains?”fn contains?<T>(r: Range<T>, n: T): Bool
type function on Range
Whether n falls inside the range. Unbounded integer ranges check only
the lower bound.
Interactive Tests
assert Range.contains?(1..5, 3)
refute Range.contains?(1..5, 5)
assert Range.contains?(1..=5, 5)
assert Range.contains?(1.25d..=2.50d, 1.50d)
Range.bounded?
Section titled “Range.bounded?”fn bounded?<T>(r: Range<T>): Bool
type function on Range
True iff the range has an upper bound. Useful as a guard before
passing an integer range to Iter.to_list.
Interactive Tests
assert Range.bounded?(1..5)
refute Range.bounded?(Range.from(1))
Range.to_string
Section titled “Range.to_string”fn to_string(r: Range<T>): String
impl Display.to_string
Range.inspect
Section titled “Range.inspect”fn inspect(r: Range<T>): String
impl Debug.inspect
Range.known_count
Section titled “Range.known_count”fn known_count(r: Range<T>): Maybe<Int>
impl Iter.known_count
Range.each_while
Section titled “Range.each_while”fn each_while(r: Range<T>, yield: (T) -> Bool): Bool
impl Iter.each_while