Julia在调用之前覆盖函数

解释问题的最简单方法是使用代码片段。

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

我想编译器正在优化一个不会持续很长时间的函数,但是我在文档中没有看到任何会导致我期待这种行为的东西,而谷歌除了文档之外什么都不返回。这里发生了什么?

回答

这看起来像是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


以上是Julia在调用之前覆盖函数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>