解释问题的最简单方法是使用代码片段。
function foo()
bar(x) = 1+x
println(bar(1)) #expecting a 2 here
bar(x) = -100000x
println(bar(1)) #expecting -100000
end
foo()
输出:
-100000
-100000
我想编译器正在优化一个不会持续很长时间的函数,但我在文档中没有看到任何会导致我期望这种行为的内容,而谷歌只返回文档。这是怎么回事?
答案 0 :(得分:10)
这看起来像是 https://github.com/JuliaLang/julia/issues/15602 的一个版本。在即将发布的 Julia 1.6 版本中,这会发出警告:
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)
你应该改用这样的匿名函数:
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