【问题标题】:Julia overwriting function before its calledJulia 在调用之前覆盖函数
【发布时间】:2021-05-16 04:09:51
【问题描述】:

解释问题的最简单方法是使用代码 sn-p。

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

我想编译器正在优化一个不会持续很长时间的函数,但我在文档中没有看到任何会导致我预期这种行为的内容,并且 Google 只返回文档。这是怎么回事?

【问题讨论】:

    标签: function julia


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 2011-09-27
      相关资源
      最近更新 更多