🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Ranges

A range is a value that stands for a sequence of integers between a first value and a last value. Ranges describe the sequence without building a list of every number in it.

A range shows its first, last, and step

IO.inspect shows each range exactly as it was written. The stepped and descending ranges keep their step in the display.

plain = 1..5
stepped = 1..10//2
down = 5..1//-1
IO.inspect(plain)
IO.inspect(stepped)
IO.inspect(down)

A comprehension lists the numbers in order

A for comprehension reads a range from its first value to its last value. The step controls which numbers appear between them.

IO.inspect(for x <- 1..5, do: x)
IO.inspect(for x <- 1..10//2, do: x)
IO.inspect(for x <- 5..1//-1, do: x)

A step changes which values appear

A step of 5 lands only on every fifth number. The odd numbers from 1 to 10 square to the second list.

starts = for n <- 0..20//5, do: n
IO.inspect(starts)
squares = for n <- 1..10//2, do: n * n
IO.inspect(squares)

Example

evens = 2..12//2
IO.inspect(evens)
values = for n <- evens, do: n
IO.inspect(values)
doubled = for n <- evens, do: n * 2
IO.inspect(doubled)

Key points

  • Range literal: write a range as first..last, such as 1..5.
  • Step: add //step after the last value to skip numbers, such as 1..10//2.
  • Descending: a negative step counts down, such as 5..1//-1.
  • Comprehension: a for comprehension can read each number from a range in order.
  • Inspect: IO.inspect shows a range in its short form, such as 1..10//2.

In this example, the range 2..12//2 is bound to evens and inspected in its short form. A comprehension then collects its numbers into the list [2, 4, 6, 8, 10, 12]. A second comprehension doubles each number, giving [4, 8, 12, 16, 20, 24].

Note

a range stores only its first value, its last value, and its step, so even a huge range stays small.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does for x <- 10..0//-5, do: x return?