From 88b689b10bd0d30cf9b2a78a61f5cfefd87bf91b Mon Sep 17 00:00:00 2001 From: Matt Bauman Date: Wed, 3 Jun 2020 08:08:09 -0500 Subject: [PATCH] fix #36116, diff(::AbstractRange) returns an Array (#36117) * fix #36116, diff(::AbstractRange) returns an Array (cherry picked from commit b49a0d5910635ff1297f9df5adf299804a908a4e) --- base/multidimensional.jl | 4 ++++ test/ranges.jl | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/base/multidimensional.jl b/base/multidimensional.jl index c2417cdf095d5..e26ae13664f2b 100644 --- a/base/multidimensional.jl +++ b/base/multidimensional.jl @@ -848,6 +848,10 @@ function diff(a::AbstractArray{T,N}; dims::Integer) where {T,N} return view(a, r1...) .- view(a, r0...) end +function diff(r::AbstractRange{T}; dims::Integer=1) where {T} + dims == 1 || throw(ArgumentError("dimension $dims out of range (1:1)")) + return T[@inbounds r[i+1] - r[i] for i in firstindex(r):lastindex(r)-1] +end ### from abstractarray.jl diff --git a/test/ranges.jl b/test/ranges.jl index 77f925b5af337..0777323b9ed66 100644 --- a/test/ranges.jl +++ b/test/ranges.jl @@ -1607,6 +1607,16 @@ end @test collect(r) == ['a','c','e','g'] end +@testset "diff of ranges, #36116" begin + for r in (0:2, 0:1:2, 0.0:1.0:2.0, LinRange(0,2,3)) + @test diff(r) == diff(collect(r)) == fill(1, 2) + @test_throws ArgumentError diff(r, dims=2) + end + for r in (0:2:5, 0.1:0.1:2.0, LinRange(0,2,33)) + @test diff(r) == diff(collect(r)) == [r[i+1] - r[i] for i in 1:length(r)-1] + end +end + @testset "Return type of indexing with ranges" begin for T = (Base.OneTo{Int}, UnitRange{Int}, StepRange{Int,Int}, StepRangeLen{Int}, LinRange{Int}) @test eltype(T(1:5)) === eltype(T(1:5)[1:2])