diff --git a/base/range.jl b/base/range.jl index bb7578f215118..c522e4d55d00e 100644 --- a/base/range.jl +++ b/base/range.jl @@ -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)). @@ -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) @@ -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) diff --git a/test/ranges.jl b/test/ranges.jl index 98f4eaa853233..e4274f84e8781 100644 --- a/test/ranges.jl +++ b/test/ranges.jl @@ -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