typestar

Ranges in Elixir

Two endpoints and a step stand in for a whole list of numbers.

# A range stores two endpoints and a step, never the whole list.
weekdays = 1..5
IO.puts("open #{Enum.count(weekdays)} days a week")
IO.puts("open on day 6? #{6 in weekdays}")

# ..// sets a step; Enum.to_list spells the range out.
gears = 10..50//8
IO.inspect(Enum.to_list(gears), label: "gear teeth")
IO.puts("total teeth: #{Enum.sum(gears)}")

How it works

  1. 1..5 builds the weekday range; Enum.count and in ask about it without expanding it.
  2. 10..50//8 adds a step, counting the gear teeth by eights.
  3. Enum.to_list spells the range out and Enum.sum folds it to one total.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
345
Tokens
80
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 3 of 3 in Lists & tuples, step 9 of 27 in Language basics.

← Previous Next →

Ranges in other languages