Range
Ranges represent a sequence of one or many, ascending or descending, consecutive integers.
Ranges can be either increasing (first <= last
) or decreasing (first > last
). Ranges are also always inclusive.
A range is represented internally as a struct. However, the most common form of creating and matching on ranges is via the ../2
macro, auto-imported from Kernel
:
iex> range = 1..3 1..3 iex> first..last = range iex> first 1 iex> last 3
A range implements the Enumerable
protocol, which means functions in the Enum
module can be used to work with ranges:
iex> range = 1..10 1..10 iex> Enum.reduce(range, 0, fn i, acc -> i * i + acc end) 385 iex> Enum.count(range) 10 iex> Enum.member?(range, 11) false iex> Enum.member?(range, 8) true
Such function calls are efficient memory-wise no matter the size of the range. The implementation of the Enumerable
protocol uses logic based solely on the endpoints and does not materialize the whole list of integers.
Summary
Types
Functions
- disjoint?(range1, range2)
Checks if two ranges are disjoint.
- new(first, last)
Creates a new range.
Types
t()
Specs
t() :: %Range{first: integer(), last: integer()}
t(first, last)
Specs
t(first, last) :: %Range{first: first, last: last}
Functions
disjoint?(range1, range2)
Specs
disjoint?(t(), t()) :: boolean()
Checks if two ranges are disjoint.
Examples
iex> Range.disjoint?(1..5, 6..9) true iex> Range.disjoint?(5..1, 6..9) true iex> Range.disjoint?(1..5, 5..9) false iex> Range.disjoint?(1..5, 2..7) false
new(first, last)
Specs
new(integer(), integer()) :: t()
Creates a new range.
Examples
iex> Range.new(-100, 100) -100..100
© 2012 Plataformatec
Licensed under the Apache License, Version 2.0.
https://hexdocs.pm/elixir/1.10.4/Range.html