Skip to content

Commit d4632bb

Browse files
committed
simplify reduction via promote_op
1 parent aea9155 commit d4632bb

File tree

1 file changed

+11
-22
lines changed

1 file changed

+11
-22
lines changed

base/reduce.jl

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -256,19 +256,12 @@ with reduction `op` over an empty array with element type of `T`.
256256
If not defined, this will throw an `ArgumentError`.
257257
"""
258258
reduce_empty(op, T) = _empty_reduce_error()
259-
reduce_empty(::typeof(+), T) = zero(T)
260-
reduce_empty(::typeof(+), ::Type{Bool}) = zero(Int)
261-
reduce_empty(::typeof(*), T) = one(T)
262-
reduce_empty(::typeof(*), ::Type{Char}) = ""
263-
reduce_empty(::typeof(&), ::Type{Bool}) = true
264-
reduce_empty(::typeof(|), ::Type{Bool}) = false
265-
266-
reduce_empty(::typeof(add_sum), T) = reduce_empty(+, T)
267-
reduce_empty(::typeof(add_sum), ::Type{T}) where {T<:SmallSigned} = zero(Int)
268-
reduce_empty(::typeof(add_sum), ::Type{T}) where {T<:SmallUnsigned} = zero(UInt)
269-
reduce_empty(::typeof(mul_prod), T) = reduce_empty(*, T)
270-
reduce_empty(::typeof(mul_prod), ::Type{T}) where {T<:SmallSigned} = one(Int)
271-
reduce_empty(::typeof(mul_prod), ::Type{T}) where {T<:SmallUnsigned} = one(UInt)
259+
reduce_empty(op::typeof(+), T) = zero(Base.promote_op(op, T, T))
260+
reduce_empty(op::typeof(add_sum), T) = zero(Base.promote_op(op, T, T))
261+
reduce_empty(op::typeof(*), T) = one(Base.promote_op(op, T, T))
262+
reduce_empty(op::typeof(mul_prod), T) = one(Base.promote_op(op, T, T))
263+
reduce_empty(op::typeof(&), ::Type{Bool}) = true
264+
reduce_empty(op::typeof(|), ::Type{Bool}) = false
272265

273266
"""
274267
Base.mapreduce_empty(f, op, T)
@@ -305,16 +298,12 @@ The default is `x` for most types. The main purpose is to ensure type stability,
305298
additional methods should only be defined for cases where `op` gives a result with
306299
different types than its inputs.
307300
"""
308-
reduce_first(op, x) = x
309-
reduce_first(::typeof(+), x::Bool) = Int(x)
310-
reduce_first(::typeof(*), x::Char) = string(x)
301+
reduce_first(op, x::T) where {T} = convert(Base.promote_op(op, T, T), x)
302+
303+
# there is no convert(String, ::Char) method
304+
reduce_first(op::typeof(*), x::Char) = string(x)
305+
reduce_first(op::typeof(mul_prod), x::Char) = string(x)
311306

312-
reduce_first(::typeof(add_sum), x) = reduce_first(+, x)
313-
reduce_first(::typeof(add_sum), x::SmallSigned) = Int(x)
314-
reduce_first(::typeof(add_sum), x::SmallUnsigned) = UInt(x)
315-
reduce_first(::typeof(mul_prod), x) = reduce_first(*, x)
316-
reduce_first(::typeof(mul_prod), x::SmallSigned) = Int(x)
317-
reduce_first(::typeof(mul_prod), x::SmallUnsigned) = UInt(x)
318307

319308
"""
320309
Base.mapreduce_first(f, op, x)

0 commit comments

Comments
 (0)