跳轉到內容

介紹 Julia/模組和包

來自 Wikibooks,開放世界中的開放書籍
Previous page
超程式設計
介紹 Julia Next page
DataFrames
模組和包

模組和包

[編輯 | 編輯原始碼]

Julia 程式碼被組織成檔案、模組和包。包含 Julia 程式碼的檔案使用 .jl 副檔名。

相關的函式和其他定義可以分組在一起並存儲在模組中。模組的結構如下所示

module MyModule
 
end

在這些行之間,您可以放置函式、型別定義、常量等等。

一個或多個模組可以儲存在一個中,這些包使用 git 版本控制系統進行管理。大多數 Julia 包,包括官方包,都儲存在 GitHub 上,按照慣例,每個 Julia 包都以“.jl”字尾命名。

安裝模組

[編輯 | 編輯原始碼]

要在您自己的機器上使用官方(註冊)的 Julia 模組,您需要從主 GitHub 網站下載並安裝包含該模組的包。所有正式註冊的包列表可以在 GitHub 上的Julia General Registry中找到,但使用 JuliaHubJulia Packages 網站搜尋包更方便。

要下載並安裝包,您可以使用 Julia 的包管理器 Pkg。首先在 REPL 中輸入右括號 ] 進入包管理器,然後使用 add 命令。您不需要使用引號或“.jl”字尾。

julia> ]
(v1.0) pkg> add Calculus
... messages
(v1.0) pkg>

(如果您沒有直接連線到網際網路,您需要在呼叫包安裝程式之前提供代理的名稱。)

提示中的(v1.0)表示您正在使用預設專案“v1.0”,位於 ~/.julia/environments/。每次釋出都會有一個新的預設專案,因此在 2022 年,您可能會看到 v1.7 或 v1.8 作為預設專案。(專案是定義 Julia 環境的典型方法,也是最常見的方法,環境是一組包,這些包共同定義了 Julia 程式碼的載入和執行方式。)

如果您想更新已有的包,請使用 up 命令

(v1.0) pkg> up
... messages
(v1.0) pkg>

有關 Julia 功能強大的包管理系統的更多資訊,請參閱完整的文件

要退出包管理器模式,請按退格鍵/刪除鍵。

使用模組/包

[編輯 | 編輯原始碼]

安裝後,要開始使用包中的函式和定義,您可以告訴 Julia 將程式碼提供給您當前的會話,使用 usingimport 語句,這些語句接受一個或多個已安裝模組的名稱

julia> using Calculus

julia>

成功後,Calculus 包中的所有定義都可供使用。如果 Calculus 模組內部的定義由作者匯出,您可以在沒有模組名稱作為字首的情況下使用它們(因為我們使用了 using

julia> derivative(sin, pi/2)
0.0

如果作者沒有匯出定義,或者我們使用 import 而不是 using,您仍然可以訪問它們,但必須輸入模組名稱作為字首

julia> Calculus.derivative(sin, pi/2)
0.0

但在這個特定示例中,這是不必要的,正如我們所見。

因此,當您編寫自己的模組時,您選擇匯出的函式可以在沒有模組名稱作為字首的情況下使用。您沒有匯出的函式仍然可以使用,但前提是它們必須加上模組名稱作為字首。例如,在名為 MyCoolModule 的模組中,mycoolfunction() 被匯出。因此,字首是可選的

julia> using MyCoolModule

julia> MyCoolModule.mycoolfunction()
"this is my cool function"

julia> mycoolfunction()
"this is my cool function"

在模組內部,此函式使用 export 語句匯出

module MyCoolModule
export mycoolfunction

function mycoolfunction()
   println("this is my cool function")
end

end

using 和 import

[編輯 | 編輯原始碼]

importusing 類似,但在某些方面有所不同,例如在如何訪問模組內部的函式方面。這是一個包含兩個函式的模組,其中一個函式被匯出

module MyModule
export mycoolfunction

function mycoolfunction()
   println("this is my cool function")
end

function mysecretfunction()
   println("this is my secret function")
end

end

使用 import 匯入模組

julia> import MyModule

julia> mycoolfunction()
ERROR: mycoolfunction not defined

julia> MyModule.mycoolfunction()
"this is my cool function"

請注意,mycoolfunction() 只能在您使用模組字首時訪問。這是因為 MyModule 模組是使用 import 而不是 using 載入的。類似地,對於 mysecretfunction() 也是如此

julia> mysecretfunction()
ERROR: mysecretfunction not defined

julia> MyModule.mysecretfunction()
this is my secret function

您可以指定一組模組

julia> using Color, Calculus, Cairo

另一個重要區別是,當您想要修改或擴充套件另一個模組中的函式時。您不能使用 using,必須 import 特定的函式。

如果您想使用其他檔案中不包含在模組中的程式碼,請使用 include() 函式。這會在當前模組的上下文中評估檔案的內容,相對於呼叫它的原始檔路徑進行搜尋。就像您只是貼上了程式碼一樣。這對於從多個較小的檔案中構建程式碼很有用。

Julia 如何找到一個模組?

[編輯 | 編輯原始碼]

Julia 會在 LOAD_PATH 變數中定義的目錄中查詢模組檔案。

julia> LOAD_PATH
3-element Array{String,1}:
 "@"      
 "@v#.#"  
 "@stdlib"

要讓它在其他地方查詢,請使用 push! 新增更多內容

julia> push!(LOAD_PATH, "/Users/me/myjuliaprojects")
3-element Array{String,1}:
 "@"      
 "@v#.#"  
 "@stdlib"                                                     
 "/Users/me/myjuliaprojects"      

並且,因為您不想每次執行 Julia 時都這樣做,請將此行放在您的啟動檔案 ~/.julia/config/startup.jl 中,它會在您啟動互動式 Julia 會話時每次執行。

Julia 會在這些目錄中查詢結構為包的檔案

ModuleName/src/file.jl

或者,如果不在包形式中(見下文),它會查詢與您的模組名稱匹配的檔名

julia> using MyModule

這將檢視 LOAD_PATH 中是否存在名為 MyModule.jl 的檔案並載入該檔案中包含的模組。

要檢視您當前專案中安裝的所有包

julia> ]
(v1.0) pkg> status
   Status `~/.julia/environments/v1.0/Project.toml`
 [c7932e45] AstroLib v0.3.0
 [9e28174c] BinDeps v0.8.8
 [159f3aea] Cairo v0.5.2
 [49dc2e85] Calculus v0.4.0
 [3da002f7] ColorTypes v0.6.7
 [5ae59095] Colors v0.8.2
 [861a8166] Combinatorics v0.6.0
 [34da2185] Compat v0.68.0
 [864edb3b] DataStructures v0.8.3
 [5789e2e9] FileIO v0.9.0
 [53c48c17] FixedPointNumbers v0.4.6
 [28b8d3ca] GR v0.31.0
 [a2bd30eb] Graphics v0.3.0
 [9fb69e20] Hiccup v0.2.1
 [a4bce56a] Iterators v0.3.1
 [e5e0dc1b] Juno v0.4.1
 ... messages 
 ...
(v1.0) pkg> 

包的結構

[編輯 | 編輯原始碼]

Julia 使用git 來組織和控制包。按照慣例,所有包都儲存在 git 儲存庫中,以“.jl”為字尾。因此,Calculus 包儲存在名為 Calculus.jl 的 Git 儲存庫中。以下是 Calculus 包在磁碟上的檔案組織方式

Calculus.jl/                                       # this is the main package directory for the Calculus package
  src/                                             # this is the subdirectory containing the source
    Calculus.jl                                    # this is the main file - notice the capital letter
      module Calculus                              # inside this file, declare the module name
        import Base.ctranspose                     # and import other packages
        export derivative, check_gradient,         # export some of the functions defined in this package
        ...
        include("derivative.jl")                   # include the contents of other files in the module
        include("check_derivative.jl")             
        include("integrate.jl")
      end                                          # end of Calculus.jl file
    derivative.jl                                  # this file contains code for working with derivatives, 
      function derivative()                        #      and is included by Calculus.jl
        ...
      end
        ...
    check_derivative.jl                            # this file concentrates on derivatives, 
      function check_derivative(f::...)            #      and is included by "include("check_derivative.jl")" in Calculus.jl
        ...
      end
      ...
    integrate.jl                                   # this file concentrates on integration, 
      function adaptive_simpsons_inner(f::Funct   # and is included by Calculus.jl
        ...
      end
      ...
    symbolic.jl                                    # concentrates on symbolic matters; included by Calculus.jl
      export processExpr, BasicVariable, ...       # these functions are available to users of the module
      import Base.show, ...                        # some Base functions are imported, 
      type BasicVariable <: AbstractVariable       # ... so that more methods can be added to them
        ...
      end
      function process(x::Expr)
        ...
      end
      ...     
  test/                                            # this directory contains the tests for the Calculus module
    runtests.jl                                    # this file runs the tests
      using Calculus                               # obviously the tests use the Calculus module... 
      using Base.Test                              # and the Base.Test module... 
      tests = ["finite_difference", ...            # the test file names are stored as strings... 
      for t in tests
        include("$(t).jl")                         # ... so that they can be evaluated in a loop 
      end
      ...
    finite_difference.jl                           # this file contains tests for finite differences, 
      @test ...                                    # ... its name is included and run by runtests.jl
      ...

標準庫

[編輯 | 編輯原始碼]

Base 和 Core 模組始終在 Julia 中可用。有一組標準(或stdlib)模組與 Julia 一起安裝,但並非所有模組都在 Julia 會話開始時載入。

如果 stdlib 模組尚未載入,請以通常的方式使用 usingimport 載入它們。

Julia 1.7 版本包含以下包

Base64 編碼和解碼 Base64 字串
CRC32c 計算 CRC-32c 校驗和
Dates 處理日期和時間
DelimitedFiles readdlm() 和 writedlm() 函式用於讀取和寫入分隔符分隔的文字資料
Distributed 在叢集中的多臺機器上工作
Downloads 下載檔案
FileWatching 監視檔案和目錄的變化
Future 實現未來版本的已有函式,這些函式將在未來版本中替換當前版本
InteractiveUtils 幫助和內省函式(通常與 REPL 一起載入)
Libdl 動態連結器
LibGit2 與 Git 庫的繫結
LinearAlgebra 線性代數函式
Logging 記錄計算的歷史記錄和進度
Markdown 支援 Markdown 文字格式約定
Mmap 處理記憶體對映陣列
Pkg 管理包的安裝
Printf C 樣式的 printf 格式化
Profile 用於分析效能的工具
Random 隨機數生成
REPL Julia 的互動式命令列 REPL
序列化 寫入和讀取 Julia 資料
SHA 提供對安全雜湊演算法 (SHA) 的支援
共享陣列 共享陣列
套接字 TCP 套接字支援
稀疏陣列 與密集陣列相比節省空間的陣列
統計 基本統計函式:stdcorvarcovmeanmedianquantile
SuiteSparse
TOML 解析 TOML 檔案
測試 測試工具
Unicode 一些 Unicode 工具
UUID 生成全域性唯一識別符號
華夏公益教科書