Skip to content

Commit 04e5d89

Browse files
authored
Recommend mean((x, y)) rather than middle((x, y)) (#147)
It seems more logical and simpler for users to recommend using the same function. Also fix checking exception.
1 parent f54010d commit 04e5d89

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

src/Statistics.jl

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,9 +107,13 @@ if !isdefined(Base, :mean)
107107
function mean(f::Number, itr::Number)
108108
f_value = try
109109
f(itr)
110-
catch MethodError
111-
rethrow(ArgumentError("""mean(f, itr) requires a function and an iterable.
112-
Perhaps you meant middle(x, y)?""",))
110+
catch err
111+
if err isa MethodError && err.f === f && err.args == (itr,)
112+
rethrow(ArgumentError("""mean(f, itr) requires a function and an iterable.
113+
Perhaps you meant mean((x, y))?"""))
114+
else
115+
rethrow(err)
116+
end
113117
end
114118
Base.reduce_first(+, f_value)/1
115119
end

test/runtests.jl

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,12 +173,18 @@ end
173173
@test isnan(@inferred mean(Iterators.filter(x -> true, Float64[])))
174174

175175
# using a number as a "function"
176-
@test_throws "ArgumentError: mean(f, itr) requires a function and an iterable.\nPerhaps you meant middle(x, y)" mean(1, 2)
176+
@test_throws "ArgumentError: mean(f, itr) requires a function and an iterable.\nPerhaps you meant mean((x, y))" mean(1, 2)
177177
struct T <: Number
178178
x::Int
179179
end
180-
(t::T)(y) = t.x * y
181-
@test @inferred mean(T(2), 3) === 6.0
180+
(t::T)(y) = t.x == 0 ? t(y, y + 1, y + 2) : t.x * y
181+
@test mean(T(2), 3) === 6.0
182+
@test_throws MethodError mean(T(0), 3)
183+
struct U <: Number
184+
x::Int
185+
end
186+
(t::U)(y) = t.x == 0 ? throw(MethodError(T)) : t.x * y
187+
@test @inferred mean(U(2), 3) === 6.0
182188
end
183189

184190
@testset "mean/median for ranges" begin

0 commit comments

Comments
 (0)