Skip to content

Commit

Permalink
allow range(start, stop; ...)
Browse files Browse the repository at this point in the history
finishes #25896
  • Loading branch information
JeffBezanson committed Oct 18, 2018
1 parent f068f21 commit da3f77d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
21 changes: 20 additions & 1 deletion base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function _colon(start::T, step, stop::T) where T
end

"""
range(start; length, stop, step=1)
range(start[, stop]; 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 @@ -58,6 +58,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 (a [`StepRange`](@ref)).
`stop` may be specified as either a positional or keyword argument.
# Examples
```jldoctest
julia> range(1, length=100)
Expand All @@ -71,11 +73,28 @@ julia> range(1, step=5, length=100)
julia> range(1, step=5, stop=100)
1:5:96
julia> range(1, 100)
1:100
julia> range(1, 10, length=101)
1.0:0.09:10.0
julia> range(1, 100, step=5)
1:5:96
```
"""
range(start; length::Union{Integer,Nothing}=nothing, stop=nothing, step=nothing) =
_range(start, step, stop, length)

range(start, stop; length::Union{Integer,Nothing}=nothing, step=nothing) =
_range2(start, step, stop, length)

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

_range2(start, step, stop, length) = _range(start, step, stop, length)

# Range from start to stop: range(a, [step=s,] stop=b), no length
_range(start, step, stop, ::Nothing) = (:)(start, step, stop)
_range(start, ::Nothing, stop, ::Nothing) = (:)(start, stop)
Expand Down
17 changes: 17 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1418,3 +1418,20 @@ end
@test @allocated(0:286.493442:360) == 0
@test @allocated(0:286:360) == 0
end

@testset "range with start and stop" begin
for starts in [-1, 0, 1, 10]
for stops in [-2, 0, 2, 100]
for lengths in [2, 10, 100]
if stops >= starts
@test range(starts, stops, length=lengths) == range(starts, stop=stops, length=lengths)
end
end
for steps in [0.01, 1, 2]
@test range(starts, stops, step=steps) == range(starts, stop=stops, step=steps)
end
end
end
# require a keyword arg
@test_throws ArgumentError range(1, 100)
end

0 comments on commit da3f77d

Please sign in to comment.