Skip to content

Commit ac9937d

Browse files
committed
Call user function only once in mean
Use an internal type to initiate promotion instead of using the type returned by user-provided function applied to the first element. This avoid calling the function twice, which can be confusing.
1 parent 81a90af commit ac9937d

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

src/Statistics.jl

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,10 @@ if !isdefined(Base, :mean)
178178
"""
179179
mean(A::AbstractArray; dims=:) = _mean(identity, A, dims)
180180

181+
struct _InitType end
182+
181183
_mean_promote(x::T, y::S) where {T,S} = convert(promote_type(T, S), y)
184+
_mean_promote(x::_InitType, y::Any) = y/1
182185

183186
# ::Dims is there to force specializing on Colon (as it is a Function)
184187
function _mean(f, A::AbstractArray, dims::Dims=:) where Dims
@@ -188,8 +191,7 @@ if !isdefined(Base, :mean)
188191
else
189192
n = mapreduce(i -> size(A, i), *, unique(dims); init=1)
190193
end
191-
x1 = f(first(A)) / 1
192-
result = sum(x -> _mean_promote(x1, f(x)), A, dims=dims)
194+
result = sum(x -> _mean_promote(_InitType(), f(x)), A, dims=dims)
193195
if dims === (:)
194196
return result / n
195197
else

0 commit comments

Comments
 (0)