Skip to content

Ranges ​

a..b goes from a to b inclusive, a..<b without b. The ends are integers. A range stores only its ends, so len, has, first, last and indexing are instant at any size.

mzs
(1..5).array  # → [1,2,3,4,5]
(1..<5).array  # → [1,2,3,4]
(0..3).len  # → 4
type(1..5)  # → "range"
str(1..5)  # → "1..5"
(1..10000000).has(3)  # → true
(1..10000000).last(2)  # → [9999999,10000000]

A descending range is empty, not reversed:

mzs
(5..1).array  # → []
(1..5).reverse  # → [5,4,3,2,1]

Functions ​

A range understands every non-mutating array function (except dig). The result is an array.

mzs
(1..5).sum  # → 15
(1..5).map { it * 2 }  # → [2,4,6,8,10]
(1..5).filter { it.even }  # → [2,4]
(1..5).find { it > 3 }  # → 4
(1..5).reduce { (a, x) -> a * x }  # → 120
(1..6).each_slice(2)  # → [[1,2],[3,4],[5,6]]
(1..3).zip(["a", "b", "c"])  # → [[1,"a"],[2,"b"],[3,"c"]]
(1..5).first(2)  # → [1,2]

Everything except len, has, first, last and indexing builds an array first, and an array is capped at a million elements. For big ranges, use seq:

mzs
(1..1_000_000_000).seq.filter { it % 7 == 0 }.take(3).array  # → [7,14,21]

step ​

step(n) goes in steps of n; without a closure it returns an array.

mzs
(0..10).step(2)  # → [0,2,4,6,8,10]
(0..10).step(3).map { it + 1 }  # → [1,4,7,10]

Other number sequences ​

FormResult
(a..b).reversedescending
a.downto(b)descending
a.step(limit, by)any step, negative too
range(lo, hi, step)an array, hi excluded
mzs
5.downto(1)  # → [5,4,3,2,1]
10.step(0, -3)  # → [10,7,4,1]
range(5)  # → [0,1,2,3,4]
range(10, 0, -2)  # → [10,8,6,4,2]

In for, match and indexes ​

mzs
for i in 1..3 { print(i) }
println()
for i in 1..<3 { print(i) }
println()
text
123
12
mzs
fn level(t) {
  match t {
    in -50..0 -> "freezing"
    in 1..15 -> "cool"
    else -> "warm"
  }
}
[level(-5), level(10), level(25)]  # → ["freezing","cool","warm"]
7 in 1..10  # → true
"hello"[1..3]  # → "ell"
[1, 2, 3, 4][1..2]  # → [2,3]