From 16aca243460938e54d8b1b4dfc6a25c0867b0660 Mon Sep 17 00:00:00 2001 From: Michael Abbott <32575566+mcabbott@users.noreply.github.com> Date: Fri, 12 Nov 2021 20:29:03 -0500 Subject: [PATCH] type-stable --- base/abstractarray.jl | 9 +++++---- test/arrayops.jl | 6 +++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/base/abstractarray.jl b/base/abstractarray.jl index 264a9a72569636..923b3b29a48b26 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -2789,19 +2789,20 @@ function mapslices(f, A::AbstractArray; dims) Aslice = A[idx1...] r1 = f(Aslice) - if r1 isa AbstractArray && ndims(r1) > 0 + res1 = if r1 isa AbstractArray && ndims(r1) > 0 n = sum(dim_mask) if ndims(r1) > n && any(ntuple(d -> size(r1,d+n)>1, ndims(r1)-n)) s = size(r1)[1:n] throw(DimensionMismatch("cannot assign slice f(x) of size $(size(r1)) into output of size $s")) end - res1 = r1 + r1 else # If the result of f on a single slice is a scalar then we add singleton # dimensions. When adding the dimensions, we have to respect the # index type of the input array (e.g. in the case of OffsetArrays) - res1 = similar(Aslice, typeof(r1), reduced_indices(Aslice, 1:ndims(Aslice))) - res1[begin] = r1 + _res1 = similar(Aslice, typeof(r1), reduced_indices(Aslice, 1:ndims(Aslice))) + _res1[begin] = r1 + _res1 end # Determine result size and allocate. We always pad ndims(res1) out to length(dims): diff --git a/test/arrayops.jl b/test/arrayops.jl index 4d910f6076989b..60cc7c5719da80 100644 --- a/test/arrayops.jl +++ b/test/arrayops.jl @@ -1203,7 +1203,7 @@ end @test mapslices(nnz, sparse(1.0I, 3, 3), dims=1) == [1 1 1] r = rand(Int8, 4,5,2) - @test mapslices(transpose, r, dims=(1,3)) == permutedims(r, (3,2,1)) + @test @inferred(mapslices(transpose, r, dims=(1,3))) == permutedims(r, (3,2,1)) @test vec(mapslices(repr, r, dims=(2,1))) == map(repr, eachslice(r, dims=3)) @test mapslices(cumsum, sparse(r[:,:,1]), dims=1) == cumsum(r[:,:,1], dims=1) @test mapslices(prod, sparse(r[:,:,1]), dims=1) == prod(r[:,:,1], dims=1) @@ -1212,8 +1212,8 @@ end @test_throws ArgumentError mapslices(identity, rand(2,3), dims=0) # previously BoundsError @test_throws ArgumentError mapslices(identity, rand(2,3), dims=(1,3)) # previously BoundsError @test_throws DimensionMismatch mapslices(x -> x * x', rand(2,3), dims=1) # explicitly caught - @test mapslices(hcat, [1 2; 3 4], dims=1) == [1 2; 3 4] # previously an error, now allowed - @test mapslices(identity, [1 2; 3 4], dims=(2,2)) == [1 2; 3 4] # previously an error + @test @inferred(mapslices(hcat, [1 2; 3 4], dims=1)) == [1 2; 3 4] # previously an error, now allowed + @test @inferred(mapslices(identity, [1 2; 3 4], dims=(2,2))) == [1 2; 3 4] # previously an error end @testset "single multidimensional index" begin