在 Julia-Lang 中包含文件的正确方法,以便考虑更新

k1n*_*ext 3 julia

我承认是朱莉娅的新手。但是,查看各种文档后,我找不到我的(可能很简单)问题的合适答案。

我从 Matlab 中了解到的

考虑src/名为main.m和的文件夹中的两个文件anotherfunc.m

function main
 anotherfunc(0)
end
Run Code Online (Sandbox Code Playgroud)

和

function anotherfunc(x)
 disp(sin(x))
end
Run Code Online (Sandbox Code Playgroud)

我会main在命令窗口中运行并查看所需的结果 ( =0)。现在,也许我改变主意并更喜欢

function otherfunc(x)
 disp(cos(x))
end
Run Code Online (Sandbox Code Playgroud)

我再跑main看看1。

我不知道 Julia 如何做完全相同的事情。我尝试了两种我认为有效的方法。

1)

这些文件是anotherfunc.jl:

function anotherfunc(x)
 print(sin(x))
end
Run Code Online (Sandbox Code Playgroud)

和(在同一目录中)main.jl:

function main()
 anotherfunc(0)
end
Run Code Online (Sandbox Code Playgroud)

现在我julia在终端开始写

julia> include("anotherfunc.jl")
anotherfunc (generic function with 1 method)

julia> include("main.jl")
main (generic function with 1 method)

julia> main()
0.0
Run Code Online (Sandbox Code Playgroud)

好的。现在我改sin到cos和GET

julia> main()
0.0
Run Code Online (Sandbox Code Playgroud)

这并不让我感到惊讶,我知道我需要另一个include,即

julia> include("anotherfunc.jl")
anotherfunc (generic function with 1 method)

julia> main()
1.0
Run Code Online (Sandbox Code Playgroud)

所以这有效但似乎很容易出错,我将来会忘记包含。

2) 我以为我会聪明写作

  function main
     include("anotherfunc.jl")
     anotherfunc(0)
    end
Run Code Online (Sandbox Code Playgroud)

但是关闭julia并重新启动它会给出

julia> main()
ERROR: MethodError: no method matching anotherfunc(::Int64)
The applicable method may be too new: running in world age 21834, while current world is 21835.
Closest candidates are:
  anotherfunc(::Any) at /some/path/anotherfunc.jl:2 (method too new to be called from this world context.)
Stacktrace:
 [1] main() at /some/path/main.jl:4
Run Code Online (Sandbox Code Playgroud)

这显然是错误的。

总结:我不知道处理拆分为多个文件的代码和开发过程中的更改的最佳过程。

hck*_*ckr 5

最简单的方法是我相信使用Modules而不是include和包Revise。

安装Revise.jl通过调用`Pkg.add(“修订”)

我们有以下Module的MyModule.jl在你的工作目录或其他目录。

module MyModule

export anotherfunc

function anotherfunc(x)
    display(sin(x))
end

end
Run Code Online (Sandbox Code Playgroud)

首先,确保存储模块的目录在您的LOAD_PATH. LOAD_PATH默认情况下不会添加 Julia 的工作目录,因此如果您将模块放在工作目录中,则调用push!(LOAD_PATH, pwd())否则调用push!(LOAD_PATH, "/path/to/your/module"). 您可以将此代码添加到您的.juliarc文件中,以免为julia您运行的每个实例调用它。

现在我们有以下主文件。

using Revise # must come before your module is loaded.
using MyModule

anotherfunc(0)
Run Code Online (Sandbox Code Playgroud)

现在更改您的文件,MyModule.jl以便anotherfunc使用cos代替sin并查看结果。

我建议你阅读https://docs.julialang.org/en/stable/manual/modules/和https://github.com/timholy/Revise.jl