朱莉娅:在函数调用前覆盖函数

4
最简单的解释问题的方法是通过一个代码片段。
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

我想编译器正在优化一个执行时间很短的函数,但我没有在文档中看到任何可以导致我期望这种行为的东西,而谷歌搜索只返回了文档。这里发生了什么?
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接