From 68dbb1d05fcd364923624d8adc1abc05cd7c99c0 Mon Sep 17 00:00:00 2001 From: Mark Kittisopikul Date: Wed, 30 Dec 2020 18:25:04 -0500 Subject: [PATCH 1/2] Add range(start, stop, length) --- base/range.jl | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/base/range.jl b/base/range.jl index b275e95c7c266..0468ba77d3507 100644 --- a/base/range.jl +++ b/base/range.jl @@ -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)). @@ -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. @@ -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 ``` @@ -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")) From fb1dad173a6ea69a53ed33b81f8c8d8bbe45e377 Mon Sep 17 00:00:00 2001 From: Mark Kittisopikul Date: Sun, 3 Jan 2021 19:02:24 -0500 Subject: [PATCH 2/2] Add tests for range(start, stop, length) --- test/ranges.jl | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/ranges.jl b/test/ranges.jl index 6fcfc18b50529..a1f930d1e10a8 100644 --- a/test/ranges.jl +++ b/test/ranges.jl @@ -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