8.7. Ranges

The range function yields an iterable range over either Integer, Long or Character bounds:

# Prints 1 2 (...) 100
foreach i in range(1, 101) {
  print(i + " ")
}

# Prints a b c d
foreach c in range('a', 'e') {
  print(c + " ")
}

let r = range(0, 6): incrementBy(2)
println("Start: " + r: from())
println("End: " + r: to())
foreach i in r {
  println(i)
}

println("Increment: " + r: increment())

The lower bound is inclusive, the upper bound is exclusive.

A range with a lower bound greater than its upper bound will be empty, except if the increment is explicitly negative:

# Prints nothing
foreach i in range(3, 0) {
  print(i + " ")
}

# Prints 3 2 1
foreach i in range(3, 0): incrementBy(-1) {
  print(i + " ")
}

# Prints 0 -2 -4
foreach i in range(0, -6):decrementBy(2) {
  print(i + " ")
}

The reversed_range function is an alias for range with an increment of -1, such that reversed_range(5, 1) is the same as range(5, 1): decrementBy(1).

When range is called with only one value, it is used as the upper bound, the lower one being a default value (0 for numbers, A for chars). For example, range(5) == range(0, 5) and range('Z') == range('A', 'Z'). In the same way, reversed_range(5) == reversed_range(5, 0).

Two ranges are equals if they have the same bounds and increment.

A range can also be defined with the literal notation [begin..end], which is equivalent to range(begin, end).