Overwriting functions in conditional statements

question

#1

I’m looking for some confirmation or correction about an interesting (to me) behavior I came across when defining functions inside conditional statements. Here’s a quick example:

julia> function test(x)
       if (x == 1)
           fn() = "this"
       elseif (x == 2)
           fn() = "that"
       else
           fn() = "the other"
       end
       fn()
       end

julia> test(1)
"the other"

julia> test(2)
ERROR: UndefVarError: fn not defined
Stacktrace:
 [1] test(::Int64) at ./REPL[44]:9

Someone coming from MATLAB might expect the following results:

julia> test(1)
"this"

julia> test(2)
"that"

Two Questions:

  1. Am I correct that the difference in behavior is related to compiled vs interpreted?
  2. Is there a way to get the MATLAB-like behavior in julia?

Thanks!


#2

No, this is because you’re defining named functions which are global in somce sense. In MATLAB you’d use function handles which is akin to Julia’s anonymous functions.

function test(x)
       if (x == 1)
           fn = ()->"this"
       elseif (x == 2)
           fn = ()->"that"
       else
           fn = ()->"the other"
       end
       fn()
       end

#3

Perfect, thanks for the clarification.