The easiest way to explain the problem is with a code snippet.
function foo()
bar(x) = 1+x
println(bar(1)) #expecting a 2 here
bar(x) = -100000x
println(bar(1)) #expecting -100000
end
foo()
OUTPUT:
-100000
-100000
I imagine that the compiler is optimizing away a function that doesn't last long, but I haven't seen anything in the docs that would cause me to expect this behavior, and Google returns nothing but the docs. What is going on here?
This looks like a version of https://github.com/JuliaLang/julia/issues/15602. In the upcoming Julia 1.6 release this gives a warning:
julia> function foo()
bar(x) = 1+x
println(bar(1)) #expecting a 2 here
bar(x) = -100000x
println(bar(1)) #expecting -100000
end
WARNING: Method definition bar(Any) in module Main at REPL[1]:2 overwritten at REPL[1]:4.
foo (generic function with 1 method)
You should use anonymous functions like this instead:
julia> function foo()
bar = x -> 1+x
println(bar(1)) #expecting a 2 here
bar = x -> -100000x
println(bar(1)) #expecting -100000
end
foo (generic function with 1 method)
julia> foo()
2
-100000
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