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
    """
    Do some other stuff instead
    """
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? :man_shrugging:t4:

Thanks for your help :+1:t3: :blush:

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.)

2 Likes

Brilliant, thanks a mil @rdeits :raised_hands:t3: :+1:t3:
The anonymous functions work now.

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