Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Ranges

ranges.livemd

Ranges

Mix.install([
  {:kino, github: "livebook-dev/kino", override: true},
  {:kino_lab, "~> 0.1.0-dev", github: "jonatanklosko/kino_lab"},
  {:vega_lite, "~> 0.1.4"},
  {:kino_vega_lite, "~> 0.1.1"},
  {:benchee, "~> 0.1"},
  {:ecto, "~> 3.7"},
  {:math, "~> 0.7.0"},
  {:faker, "~> 0.17.0"},
  {:utils, path: "#{__DIR__}/../utils"}
])

Navigation

Return Home Report An Issue

Ranges

Ranges are useful for representing an ascending or descending sequence of numbers, without needing to manually type each number in a list.

For example, you could have a range from 1 to 10.

1..10

flowchart LR
  1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 7 --> 8 --> 9 --> 10

or 5 to -5.

5..-5
flowchart LR
  5 --> 4 --> 3 --> 2 --> 1 --> 0 --> -1 --> -2 --> -3 --> -4 --> -5

You can visualize a range as representing an ascending or descending list of integers.

On its own, it might not seem like much. But ranges will be incredibly useful with the Enum module. You’ll learn more about the Enum module in a future lesson. For now, it’s enough to understand the relationship between ranges and lists.

For example the range 1..5 equates to [1, 2, 3, 4, 5] as a list.

To establish that relationship, you can use Enum.to_list/1 to convert a range from the list.

Enum.to_list(1..5)

Ranges can have a step. By default ranges have a step of 1. That means that by default they include each whole number in the range.

You can override the default step of the range using //:

0..10//2

This creates a range from 0 to 10 with a step of 2.

0 --> 2 --> 4 --> 6 --> 8 --> 10

That means the range 0..10//2 correlates to the list [0, 2, 4, 6, 8, 10]

Here’s the same range converted into a list to help you visualize it. Once again, you will learn more about what Enum.to_list is in a future lesson.

Enum.to_list(0..10//2)

Your Turn

In the Elixir cell below, use Enum.to_list to convert a range from 3 to 9 with a step of 3 into a list. Replace nil with your answer.

answer = nil

Utils.feedback(:range_to_list, answer)

Commit Your Progress

Run the following in your command line from the project folder to track and save your progress in a Git commit.

$ git add .
$ git commit -m "finish ranges section"