Wow, that’s really weird. Even worse is that even if you didn’t get an UndefVarError
, you’d still get the wrong answer due to the issue discussed here: Conditional function definition
The fix for both problems is to use an anonymous function:
using Statistics: std, mean, median, var
function foo(a,b,c)
"""
Do some stuff
"""
if a > 0
if a == 1
bar = x -> std(x, corrected=false)
elseif a == 2
bar = x -> var(x, corrected=false)
elseif a == 3
bar = x -> mean(abs.(x .- mean(x)))
elseif a == 4
bar = x -> median(abs.(x .- median(x)))
end
else
"""
Do some other stuff instead
"""
end
return c*bar(b)
end
(this will still error unless a
is 1, 2, 3, or 4, in which case bar
really is undefined.)