本文介绍了如何评估 Julia 中的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

i = 50
function test()
  i = 10
  eval(:i)
end
test()  # => 50

为什么这会评估为全局 i 而不是本地的?有没有办法让它评估到本地?

Why does this evaluate to the global i instead of the local one? Is there a way to make it evaluate to the local?

推荐答案

你不能.Julia 的 eval 总是评估当前模块范围的代码,而不是本地范围.在本地范围内调用 eval 是一种反模式和性能杀手.但是,您可以构造一个新函数,其中包含一些引用本地范围的用户代码,然后调用该函数.例如:

You can't. Julia's eval always evaluates code the current module's scope, not your local scope. Calling eval in local scope is an anti-pattern and a performance killer. You can, however, construct a new function which includes a bit of user code that refers to local scope and then call that function. For example:

# user-supplied expression
expr = :(i^2 + 1)

# splice into function body
test = @eval function ()
    i = 10
    $expr
end

现在你可以调用 test:

julia> test()
101

为什么这比在问题中调用 test 内的 eval 更好?因为原来,每次调用test都需要调用eval,而在这种用法中,eval只在定义测试;当 test 被调用时,没有 eval 完成.因此,虽然您可以在运行时"调用 eval 在当您的应用程序运行时,获取用户输入"的意义上它不是在函数构造的意义上称为在运行时"调用该用户输入.前者很好,而后者显然是一种反模式.

Why is this better than calling eval inside of test as in the question? Because in the original, eval needs to be called every time you call test whereas in this usage, eval is only called once when defining test; when test is called no eval is done. So while you may call eval "at run time" in the sense of "while your application is running, getting user input" it is not called "at run time" in the sense of when the function constructed with that user input is called. The former is fine, whereas the latter as distinctly an anti-pattern.

这篇关于如何评估 Julia 中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:39