From 4b83a640b5e258c770534e5d66a6fae0d10b23a9 Mon Sep 17 00:00:00 2001 From: N5N3 <2642243996@qq.com> Date: Fri, 7 Jan 2022 06:33:00 +0800 Subject: [PATCH] Resolve instability from `reducedim_init` (#43467) --- base/reducedim.jl | 6 +++--- test/reducedim.jl | 8 ++++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/base/reducedim.jl b/base/reducedim.jl index c04a6c1b984f6..02b2345038bcc 100644 --- a/base/reducedim.jl +++ b/base/reducedim.jl @@ -139,7 +139,7 @@ for (f1, f2, initval, typeextreme) in ((:min, :max, :Inf, :typemax), (:max, :min if isempty(A1) # If the slice is empty just return non-view version as the initial array - return copy(A1) + return map(f, A1) else # otherwise use the min/max of the first slice as initial value v0 = mapreduce(f, $f2, A1) @@ -148,9 +148,9 @@ for (f1, f2, initval, typeextreme) in ((:min, :max, :Inf, :typemax), (:max, :min Tr = v0 isa T ? T : typeof(v0) # but NaNs and missing need to be avoided as initial values - if (v0 == v0) === false + if v0 isa Number && isnan(v0) # v0 is NaN - v0 = $initval + v0 = oftype(v0, $initval) elseif isunordered(v0) # v0 is missing or a third-party unordered value Tnm = nonmissingtype(Tr) diff --git a/test/reducedim.jl b/test/reducedim.jl index f009a2384ca51..db60d353ae95e 100644 --- a/test/reducedim.jl +++ b/test/reducedim.jl @@ -445,8 +445,8 @@ end @testset "argmin/argmax" begin B = reshape(3^3:-1:1, (3, 3, 3)) - @test B[argmax(B, dims=[2, 3])] == maximum(B, dims=[2, 3]) - @test B[argmin(B, dims=[2, 3])] == minimum(B, dims=[2, 3]) + @test B[argmax(B, dims=[2, 3])] == @inferred(maximum(B, dims=[2, 3])) + @test B[argmin(B, dims=[2, 3])] == @inferred(minimum(B, dims=[2, 3])) end @testset "in-place reductions with mismatched dimensionalities" begin @@ -506,3 +506,7 @@ end @test r_red == [3] end end + +@testset "type stability (issue #43461)" begin + @test (@inferred maximum(Float64, reshape(1:4,2,:); dims = 2)) == reshape([3,4],2,1) +end