本页尚未翻译,因此以英文显示。 参与翻译

range

A lazy sequence of integers from start (inclusive) to end (exclusive), stepping by any amount.

Iterable<int> range(int start, [int? end, int step = 1])

Lecture

range generates integers on demand, using a sync* generator — nothing is allocated up front. Called with one argument, range(4) counts 0, 1, 2, 3 (i.e. 0 up to, but not including, start). Called with two, range(1, 4) counts 1, 2, 3. A third argument sets the step — including a negative step to count downward, e.g. range(4, 1, -1) gives 4, 3, 2.

Because it's lazy, range(1000000) is essentially free to create — the million integers only get produced as something downstream (usually .take(n)) actually pulls them. This makes range the go-to source for demonstrating laziness, and a handy stand-in whenever you need "the first N things" without building a real collection first.

Unlike FxTS's range, which is a finite generator over numbers, this port keeps the same finite contract — there's no unbounded/infinite form here (that's cycle's job). If you want an endless counter, pair range with cycle and take.

Demo 1 · Counting up, down, and by steps

Demo 2 · Laziness in a chain

range(1000000) produces nothing up front — only the 4 elements take(4) asks for actually run through map:

Try it yourself

Exercise: build the even numbers from 2 to 10 inclusive using range's step argument.

Related: repeat — a fixed value repeated n times · cycle — repeat a whole sequence forever · take — bound how much of a range you pull · fx — the chain range is usually wrapped in