In Julia 1.4.1, if I define a function in a global scope, modifications after "if false" statements do not affect it, as expected:
test()=0
if false
test()=1
end
println(test())
This prints "0", as it should. However, when I enclose this code within a local scope, the behavior changes:
function main()
test()=0
if false
test()=1
end
println(test())
end
main()
This now prints "1" which I did not expect. If I change "test" to be an array or a float I observe no modification as expected, i.e. the problem does not occur. Why does Julia behave this way for functions?
The solution is to use anonymous functions in cases like this:
function main()
test = () -> 0
if false
test = () -> 1
end
println(test())
end
julia> main()
0
As for the why, this gets to the core of what it means to define and redefine a particular method of a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With