Skip to content

Commit b49a0d5

Browse files
authored
fix #36116, diff(::AbstractRange) returns an Array (#36117)
* fix #36116, diff(::AbstractRange) returns an Array
1 parent 65c2a03 commit b49a0d5

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

base/multidimensional.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -848,6 +848,10 @@ function diff(a::AbstractArray{T,N}; dims::Integer) where {T,N}
848848

849849
return view(a, r1...) .- view(a, r0...)
850850
end
851+
function diff(r::AbstractRange{T}; dims::Integer=1) where {T}
852+
dims == 1 || throw(ArgumentError("dimension $dims out of range (1:1)"))
853+
return T[@inbounds r[i+1] - r[i] for i in firstindex(r):lastindex(r)-1]
854+
end
851855

852856
### from abstractarray.jl
853857

test/ranges.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1607,6 +1607,16 @@ end
16071607
@test collect(r) == ['a','c','e','g']
16081608
end
16091609

1610+
@testset "diff of ranges, #36116" begin
1611+
for r in (0:2, 0:1:2, 0.0:1.0:2.0, LinRange(0,2,3))
1612+
@test diff(r) == diff(collect(r)) == fill(1, 2)
1613+
@test_throws ArgumentError diff(r, dims=2)
1614+
end
1615+
for r in (0:2:5, 0.1:0.1:2.0, LinRange(0,2,33))
1616+
@test diff(r) == diff(collect(r)) == [r[i+1] - r[i] for i in 1:length(r)-1]
1617+
end
1618+
end
1619+
16101620
@testset "Return type of indexing with ranges" begin
16111621
for T = (Base.OneTo{Int}, UnitRange{Int}, StepRange{Int,Int}, StepRangeLen{Int}, LinRange{Int})
16121622
@test eltype(T(1:5)) === eltype(T(1:5)[1:2])

0 commit comments

Comments
 (0)