Skip to content

Commit 9704320

Browse files
committed
allow range(start, stop; ...)
finishes #25896
1 parent f068f21 commit 9704320

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

base/range.jl

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ function _colon(start::T, step, stop::T) where T
4646
end
4747

4848
"""
49-
range(start; length, stop, step=1)
49+
range(start[, stop]; length, stop, step=1)
5050
5151
Given a starting value, construct a range either by length or from `start` to `stop`,
5252
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
5858
If `step` and `stop` are provided and `length` is not, the overall range length will be computed
5959
automatically such that the elements are `step` spaced (a [`StepRange`](@ref)).
6060
61+
`stop` may be specified as either a positional or keyword argument.
62+
6163
# Examples
6264
```jldoctest
6365
julia> range(1, length=100)
@@ -71,11 +73,25 @@ julia> range(1, step=5, length=100)
7173
7274
julia> range(1, step=5, stop=100)
7375
1:5:96
76+
77+
julia> range(1, 10, length=101)
78+
1.0:0.09:10.0
79+
80+
julia> range(1, 100, step=5)
81+
1:5:96
7482
```
7583
"""
7684
range(start; length::Union{Integer,Nothing}=nothing, stop=nothing, step=nothing) =
7785
_range(start, step, stop, length)
7886

87+
range(start, stop; length::Union{Integer,Nothing}=nothing, step=nothing) =
88+
_range2(start, step, stop, length)
89+
90+
_range2(start, ::Nothing, stop, ::Nothing) =
91+
throw(ArgumentError("At least one of `length` or `step` must be specified"))
92+
93+
_range2(start, step, stop, length) = _range(start, step, stop, length)
94+
7995
# Range from start to stop: range(a, [step=s,] stop=b), no length
8096
_range(start, step, stop, ::Nothing) = (:)(start, step, stop)
8197
_range(start, ::Nothing, stop, ::Nothing) = (:)(start, stop)

test/ranges.jl

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1418,3 +1418,20 @@ end
14181418
@test @allocated(0:286.493442:360) == 0
14191419
@test @allocated(0:286:360) == 0
14201420
end
1421+
1422+
@testset "range with start and stop" begin
1423+
for starts in [-1, 0, 1, 10]
1424+
for stops in [-2, 0, 2, 100]
1425+
for lengths in [2, 10, 100]
1426+
if stops >= starts
1427+
@test range(starts, stops, length=lengths) == range(starts, stop=stops, length=lengths)
1428+
end
1429+
end
1430+
for steps in [0.01, 1, 2]
1431+
@test range(starts, stops, step=steps) == range(starts, stop=stops, step=steps)
1432+
end
1433+
end
1434+
end
1435+
# require a keyword arg
1436+
@test_throws ArgumentError range(1, 100)
1437+
end

0 commit comments

Comments
 (0)