Skip to content

Commit

Permalink
Use reduce_first instead of reduce_empty
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf committed Feb 17, 2020
1 parent 5a7963d commit 8db9ad6
Showing 1 changed file with 7 additions and 16 deletions.
23 changes: 7 additions & 16 deletions src/mapreduce.jl
Original file line number Diff line number Diff line change
Expand Up @@ -299,21 +299,14 @@ _valof(::Val{D}) where D = D
_accumulate(op, a, _maybe_val(dims), init)

@inline function _accumulate(op::F, a::StaticArray, dims::Union{Val,Colon}, init) where {F}
# Adjoin the initial value to `op`:
rf(x, y) = x isa _InitialValue ? Base.reduce_first(op, y) : op(x, y)

if isempty(a)
if init isa _InitialValue
# Deliberately not using `return_type` here, since this `eltype` is
# exact for the singleton element case (i.e., `op` will not be called).
return similar_type(a)()
else
# Using the type that _would_ be used if `size(a, dims) == 1`:
T = return_type(op, Tuple{typeof(init), eltype(a)})
return similar_type(a, T)()
end
T = return_type(rf, Tuple{typeof(init), eltype(a)})
return similar_type(a, T)()
end

# Adjoin the initial value to `op`:
rf(x, y) = x isa _InitialValue ? y : op(x, y)

# StaticArrays' `reduce` is `foldl`:
results = _reduce(
a,
Expand All @@ -340,7 +333,5 @@ _valof(::Val{D}) where D = D
return similar_type(a, eltype(data))(data)
end

@inline Base.cumsum(a::StaticArray; kw...) =
accumulate(Base.add_sum, a; init = Base.reduce_empty(Base.add_sum, eltype(a)), kw...)
@inline Base.cumprod(a::StaticArray; kw...) =
accumulate(Base.mul_prod, a; init = Base.reduce_empty(Base.mul_prod, eltype(a)), kw...)
@inline Base.cumsum(a::StaticArray; kw...) = accumulate(Base.add_sum, a; kw...)
@inline Base.cumprod(a::StaticArray; kw...) = accumulate(Base.mul_prod, a; kw...)

0 comments on commit 8db9ad6

Please sign in to comment.