閉包簡介
函式是 Julia 程式設計的重要組成部分。它們可以直接在模組中定義,在這種情況下,函式稱為頂級。但是函式也可以在其他函式中定義。這些功能稱為“ 閉包 ”。
閉包捕獲外部函式中的變數。頂級函式只能使用其模組,函式引數或區域性變數中的全域性變數:
x = 0 # global
function toplevel(y)
println("x = ", x, " is a global variable")
println("y = ", y, " is a parameter")
z = 2
println("z = ", z, " is a local variable")
end
另一方面,閉包可以使用除了捕獲的外部函式的變數之外的所有變數:
x = 0 # global
function toplevel(y)
println("x = ", x, " is a global variable")
println("y = ", y, " is a parameter")
z = 2
println("z = ", z, " is a local variable")
function closure(v)
println("v = ", v, " is a parameter")
w = 3
println("w = ", w, " is a local variable")
println("x = ", x, " is a global variable")
println("y = ", y, " is a closed variable (a parameter of the outer function)")
println("z = ", z, " is a closed variable (a local of the outer function)")
end
end
如果我們執行 c = toplevel(10)
,我們會看到結果是
julia> c = toplevel(10)
x = 0 is a global variable
y = 10 is a parameter
z = 2 is a local variable
(::closure) (generic function with 1 method)
請注意,此函式的尾部表示式本身就是一個函式; 也就是說,關閉。我們可以像關閉任何其他函式一樣呼叫閉包 c
:
julia> c(11)
v = 11 is a parameter
w = 3 is a local variable
x = 0 is a global variable
y = 10 is a closed variable (a parameter of the outer function)
z = 2 is a closed variable (a local of the outer function)
請注意,即使 toplevel
已經返回,c
仍然可以從 toplevel
呼叫訪問變數 y
和 z
! 每個閉包,即使是由相同函式返回的閉包,也會關閉不同的變數。我們可以再次呼叫 toplevel
julia> d = toplevel(20)
x = 0 is a global variable
y = 20 is a parameter
z = 2 is a local variable
(::closure) (generic function with 1 method)
julia> d(22)
v = 22 is a parameter
w = 3 is a local variable
x = 0 is a global variable
y = 20 is a closed variable (a parameter of the outer function)
z = 2 is a closed variable (a local of the outer function)
julia> c(22)
v = 22 is a parameter
w = 3 is a local variable
x = 0 is a global variable
y = 10 is a closed variable (a parameter of the outer function)
z = 2 is a closed variable (a local of the outer function)
請注意,儘管 d
和 c
具有相同的程式碼,並且傳遞相同的引數,但它們的輸出是不同的。它們是截然不同的封閉物。