# Function definition throwing UndefVarError

Hello,

I have a function which follows the condensed, simplified format shown below.

``````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
"""
"""
end

return c*bar(b)
end
``````

When I call the `foo` function for `a = 0` or `a = 1`, it runs fine.
However, for `a > 2` an error message appears for an undefined variable:
`ERROR: UndefVarError: bar not defined`

Each of these `bar` functions runs normally when called in the REPL…

Can anyone tell me why I might be getting this error for `a` values greater than 1? Thanks for your help  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
"""
"""
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.)

2 Likes

Brilliant, thanks a mil @rdeits  The anonymous functions work now.

I wonder why my original approach didn’t work though…