Dear Julia users,
I must confess to finding the following behaviour extremely puzzling - I suspect it’s related to scoping, but I can’t make heads or tails of it. Here’s a simple function featuring nested functions:
function test1(arg)
if (arg==1)
f(x) = 3*x
f(1)
else
a = 5
f(x) = a*x
f(2)
end
end
Now calling test1(1) gives me:
ERROR: UndefVarError: a not defined
and test(2) gives me
ERROR: UndefVarError: f not defined
Executing the above code directly in the REPL works fine, though, ie:
arg = 1
if (arg==1)
f(x) = 3*x
f(1)
else
a = 5
f(x) = a*x
f(2)
end
Here’s a variant that fails in a different manner:
function test2(arg)
f(x) = x
if (arg==1)
f(x) = 3*x
f(1)
else
a = 5
f(x) = a*x
f(2)
end
end
Now test2(1) still fails with the same error but test2(2) works.
Finally, this variant works fine:
function test3(arg)
if (arg==1)
f = (x) -> 3*x
f(1)
else
a = 3
f = (x) -> a*x
f(2)
end
end
This on julia 1.0.3. What gives?
Thanks!