Skip to content

Fix reduction over empty array #780

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/mapreduce.jl
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,17 @@ end
@inline _mapreduce(args::Vararg{Any,N}) where N = _mapfoldl(args...)

@generated function _mapfoldl(f, op, dims::Colon, init, ::Size{S}, a::StaticArray...) where {S}
if prod(S) == 0
if init === _InitialValue
if length(a) == 1
return :(Base.mapreduce_empty(f, op, $(eltype(a[1]))))
else
return :(throw(ArgumentError("reducing over an empty collection is not allowed")))
end
else
return :init
end
end
tmp = [:(a[$j][1]) for j ∈ 1:length(a)]
expr = :(f($(tmp...)))
if init === _InitialValue
Expand Down
38 changes: 38 additions & 0 deletions test/mapreduce.jl
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,44 @@ using Statistics: mean
@test mapfoldl(-, +, sv1; init=0) === mapfoldl(-, +, v1, init=0)
end

@testset "empty array" begin
# issue #778
@test iszero(SVector{0,Int}())

@testset "$fold" for fold in [reduce, foldl]
@test fold(+, SVector{0,Bool}()) === 0
@test fold(nothing, SVector{0,Int}(), init=:INIT) === :INIT
end

@testset "$mapfold" for mapfold in [mapreduce, mapfoldl]
@test mapfold(identity, +, SVector{0,Bool}()) === 0
@test mapfold(abs, +, SVector{0,Bool}()) === 0
@test mapfold(nothing, nothing, SVector{0,Int}(), init=:INIT) === :INIT
end

@test mapreduce(
(a, b) -> a + b,
(a, b) -> a * b,
SVector{0,Int}(),
SVector{0,Int}();
init = :INIT,
) == :INIT

# When there are multiple inputs, the error is thrown by
# StaticArrays.jl:
@test_throws(
ArgumentError("reducing over an empty collection is not allowed"),
mapreduce((a, b) -> a + b, (a, b) -> a * b, SVector{0,Int}(), SVector{0,Int}())
)

# When the mapping and/or reducing functions are unsupported,
# the error is thrown by `Base.mapreduce_empty`:
@test_throws(
ArgumentError("reducing over an empty collection is not allowed"),
mapreduce(nothing, nothing, SVector{0,Int}())
)
end

@testset "implemented by [map]reduce and [map]reducedim" begin
I, J, K = 2, 2, 2
OSArray = SArray{Tuple{I,J,K}} # original
Expand Down