The Range Operator
The range operator (..) in Elixir introduces a convenient way of defining sequences of successive integers. This section will explore the range operator, demonstrating its various uses from simple range definitions to utilization in functions for processing sequences.
Understanding the Range Operator ..
In Elixir, a range is created by two integers separated by the .. operator. This sequence includes both the start and end points. For example, 1..5 creates a range of integers from 1 to 5 inclusive. 5..1 does the same but in reverse order.
Ranges in Elixir are considered as enumerables, which means they can be used with the Enum module to iterate over the sequence of numbers. This capability makes the range operator a versatile tool in various situations involving sequences of numbers.
The examples below use a couple of functions from the Enum module as a preview. The Enumerables chapter covers Enum in detail. For now it is enough to know that Enum offers functions to walk through things like lists or ranges.
|
iex> 1..5
1..5
iex> Enum.to_list(1..5)
[1, 2, 3, 4, 5]
In the code above, the first command creates a range from 1 to 5. The second command converts the range into a list using the Enum.to_list/1 function.