Skip to content

Commit 5705dc3

Browse files
authored
Fix sum(::AbstractArray{<:AbstractMutable}; dims) (#310)
1 parent 3f811de commit 5705dc3

2 files changed

Lines changed: 24 additions & 2 deletions

File tree

src/dispatch.jl

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,18 @@
1313

1414
abstract type AbstractMutable end
1515

16-
function Base.sum(a::AbstractArray{<:AbstractMutable}; kwargs...)
17-
return operate(sum, a; kwargs...)
16+
function Base.sum(
17+
a::AbstractArray{T};
18+
dims = :,
19+
init = zero(promote_operation(+, T, T)),
20+
) where {T<:AbstractMutable}
21+
if dims !== Colon()
22+
# We cannot use `mapreduce` with `add!!` instead of `Base.add_mul` like
23+
# `operate(sum, ...)` because the same instance given at `init` is used
24+
# at several places.
25+
return mapreduce(identity, Base.add_sum, a; dims, init)
26+
end
27+
return operate(sum, a; init)
1828
end
1929

2030
# When doing `x'y` where the elements of `x` and/or `y` are arrays, redirecting

test/dispatch.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,15 @@ end
131131
# MA is at least 10-times better than no MA for this example
132132
@test 10 * with_init < no_ma
133133
end
134+
135+
@testset "sum_with_init_and_dims" begin
136+
x = reshape(convert(Vector{DummyBigInt}, 1:12), 3, 4)
137+
X = reshape(1:12, 3, 4)
138+
for dims in (1, 2, :, 1:2, (1, 2))
139+
# Without (; init)
140+
@test MA.isequal_canonical(sum(x; dims), DummyBigInt.(sum(X; dims)))
141+
# With (; init)
142+
y = sum(x; init = DummyBigInt(0), dims)
143+
@test MA.isequal_canonical(y, DummyBigInt.(sum(X; dims)))
144+
end
145+
end

0 commit comments

Comments
 (0)