8.17.0.1

3.7 Ranges🔗ℹ

As we saw in Iteration, some ranges can be useful when used as sequences. More generally, ranges represent a contiguous set of integers between two points, and they support constant-time operations that work with integers. Ranges are typically created with the .., ..=, <.., or <..= operators, where a prefix < alludes to an exclusive (as opposed to inclusive) starting point, and a suffix = alludes to an inclusive (as opposed to exclusive) ending point. There are also Range functions that correspond to these operators.

A range supports membership tests with the in operator.

def natural_numbers = 0..

> 0 in natural_numbers

#true

> 5 in natural_numbers

#true

> -5 in natural_numbers

#false

A range is said to enclose another range when it contains every integer that the other range contains.

def integers = ..

> integers.encloses(natural_numbers)

#true

Ranges in the forms x .. y, x ..= y, or x .. satisfy SequenceRange and can be used as sequences, as already shown in Iteration. Moreover, ranges in the forms x .. y or x ..= y also satisfy ListRange and are listable (see Lists).

def less_than_five = 0..5

def up_to_five = 0..=5

> [& less_than_five]

[0, 1, 2, 3, 4]

> [& up_to_five]

[0, 1, 2, 3, 4, 5]