Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,43 @@ range(start; length::Union{Integer,Nothing}=nothing, stop=nothing, step=nothing)
range(start, stop; length::Union{Integer,Nothing}=nothing, step=nothing) =
_range2(start, step, stop, length)

"""
range(start => stop, length)

Given a `start` to `stop` [`Pair`](@ref) and an integer `length`,
construct a range iterator of `length` elements whose first element is `start`
and last element is `stop`.

This is distinct from `start:stop` where `stop` may not be the last
element. Also, in this form `step` is not assumed to be 1. `length` must be an
`Integer` and cannot be `nothing`.

No keywords are accepted when `start` and `stop` are provided as a [`Pair`](@ref).

Special care is taken to ensure intermediate values are computed rationally.
To avoid this induced overhead, see the [`LinRange`](@ref) constructor.

!!! compat "Julia 1.7"
Providing `start => stop` as a `Pair` requires at least Julia 1.7.

# Examples
```jldoctest
julia> range(1 => 5, 3)
1.0:2.0:5.0

julia> range(0 => 100, 101)
0.0:1.0:100.0

julia> range(5 => 3, 3)
5.0:-1.0:3.0
```
"""
range(start_stop::Pair, length::Integer) =
_range(start_stop.first, nothing, start_stop.second, length)

range(start_stop::Pair, length::Nothing = nothing) =
throw(ArgumentError("`length` must be specified after $start_stop"))

_range2(start, ::Nothing, stop, ::Nothing) =
throw(ArgumentError("At least one of `length` or `step` must be specified"))

Expand Down
12 changes: 12 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1610,6 +1610,18 @@ end
@test_throws ArgumentError range(1, 100)
end

@testset "range with start => stop Pair argument" begin
for starts in [-1, 0, 1, 10]
for stops in [-2, 0, 2, 100]
for lengths in [2, 10, 100]
@test range( starts => stops, lengths) === range(starts, stops; length = lengths)
end
end
end
@test_throws ArgumentError range( 1 => 5 )
@test_throws ArgumentError range( -1 => -5 , nothing )
end

@testset "Reverse empty ranges" begin
@test reverse(1:0) === 0:-1:1
@test reverse(Base.OneTo(0)) === 0:-1:1
Expand Down