julia - 如何防止模块中的全局变量或数组?
问题描述
我从 Fortran 来到 Julia。我知道 Julia 想要阻止使用全局变量。但问题是,如何防止在模块中使用全局变量?
例如,在以下模块中,
module Mod
global AAA=zeros(1000000000)
function f(x)
change the most up to date AAA with x in some way.
return nothing
end
function g(x)
using the most up to date AAA, then change/update AAA with x in some way.
return nothing
end
end
在上面的例子中,我需要更新非常大的数组 AAA,所以我把 AAA 放在了全局中。因此 f(x) 和 g(x) 可以使用最新的 AAA 并进一步更新它们。
现在由于 Julia 不鼓励使用全局变量,所以在我的情况下,我该怎么办?
我的意思是,我是否将 AAA 放在 f(x) 和 g(x) 的参数中,从而使它们变为 f(x,AAA) 和 g(x,AAA)?
在参数中传递像 AAA 这样非常大的数组真的比将 AAA 仅仅作为全局变量更快吗?
解决方案
可以将相关数组传递给函数。这是您的伪代码的更新版本。
module Mod
AAA=zeros(1000000000)
function f!(ba, x) # the ! mark to indicate that ba will be updated
ba[1]=x
return nothing
end
function g!(ba, x)
ba[1] +=x
return nothing
end
function example()
f!(AAA,1)
g!(AAA,2)
@show(AAA[1])
end
end
我正在使用我的手机,所以可能会有一些拼写错误,我无法进行基准测试,但如果你想说服自己将数组作为参数传递没有任何惩罚,你可以这样做。
添加一个 ! 当函数改变参数的内容时。此外,更改的参数放在列表中的第一位。当然,这些只是约定,但它使其他人更容易理解您的代码的意图。
推荐阅读
- google-cloud-platform - 为什么错误报告仪表板中没有报告云功能错误?
- java - 如何使用计时器中的值在我的游戏中建立评分系统?- 爪哇
- python - 无法加载 Python C 扩展
- javascript - 在 Lodash 中合并(内部连接)只保留具有公共键的行
- tsql - Power Automate - 执行存储过程 (V2) - 始终返回 HTTP 错误 400
- javascript - 尝试使用 jquery 和会话 cookie 创建一个记住我的功能,但应用程序在再次运行时甚至不会加载
- r - 如何使用“是”或“否”重命名逻辑值(TRUE 或 FALSE)并将 distinct() 应用于 FALSE 值
- javascript - 使 chrome 扩展能够查询浏览器页面的窗口
- macos - Spotlight 货币转换器未更新
- dafny - 断言和集合基数