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..5builds the weekday range;Enum.countandinask about it without expanding it.10..50//8adds a step, counting the gear teeth by eights.Enum.to_listspells the range out andEnum.sumfolds it to one total.
Keywords and builtins used here
EnumIO
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.
Step 3 of 3 in Lists & tuples, step 9 of 27 in Language basics.