Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add range(start, stop, length) #39055

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
10 changes: 9 additions & 1 deletion base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ function _colon(start::T, step, stop::T) where T
end

"""
range(start[, stop]; length, stop, step=1)
range(start[, stop[, length]]; length, stop, step=1)

Given a starting value, construct a range either by length or from `start` to `stop`,
optionally with a given step (defaults to 1, a [`UnitRange`](@ref)).
Expand All @@ -59,6 +59,8 @@ automatically such that there are `length` linearly spaced elements in the range
If `step` and `stop` are provided and `length` is not, the overall range length will be computed
automatically such that the elements are `step` spaced.

If `start`, `stop`, and `length` are specified by position, no keywords are permitted.

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

Expand All @@ -84,6 +86,9 @@ julia> range(1, step=5, stop=100)
julia> range(1, 10, length=101)
1.0:0.09:10.0

julia> range(1, 10, 101)
1.0:0.09:10.0

julia> range(1, 100, step=5)
1:5:96
```
Expand All @@ -94,6 +99,9 @@ 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::Union{Integer,Nothing}) =
_range(start, nothing, stop, length)

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

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

@testset "range wtih start, stop, and length" 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, stop=stops, length=lengths)
end
@test range(starts, stops, nothing) === range(starts, stop=stops)
end
end
end

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