我使用 let 块在 Julia 中拼凑了一个闭包。
counter = let
local counter = 0 # local variable
f() = counter += 1 # returned function
end
counter(); counter(); counter()
print(counter()) # 4
Run Code Online (Sandbox Code Playgroud)
这是朱莉娅的犹太洁食吗?
Bog*_*ski 10
这是有效的。以下是获得类似事物的两种替代方法:
julia> function get_counter()
counter = 0
return () -> (counter += 1)
end
get_counter (generic function with 1 method)
julia> c1 = get_counter()
#1 (generic function with 1 method)
julia> c1()
1
julia> c1()
2
julia> c1()
3
julia> mutable struct Counter
counter::Int
Counter() = new(0)
end
julia> (c::Counter)() = (c.counter += 1)
julia> c2 = Counter()
Counter(0)
julia> c2()
1
julia> c2()
2
julia> c2()
3
Run Code Online (Sandbox Code Playgroud)
不同之处在于c2类型稳定,而您的counter和c1不是类型稳定的:
julia> @code_warntype counter()
Variables
#self#::var"#f#1"
counter::Union{}
Body::Any
1 ? %1 = Core.getfield(#self#, :counter)::Core.Box
? %2 = Core.isdefined(%1, :contents)::Bool
??? goto #3 if not %2
2 ? goto #4
3 ? Core.NewvarNode(:(counter))
??? counter
4 ? %7 = Core.getfield(%1, :contents)::Any
? %8 = (%7 + 1)::Any
? %9 = Core.getfield(#self#, :counter)::Core.Box
? Core.setfield!(%9, :contents, %8)
??? return %8
julia> @code_warntype c1()
Variables
#self#::var"#2#3"
counter::Union{}
Body::Any
1 ? %1 = Core.getfield(#self#, :counter)::Core.Box
? %2 = Core.isdefined(%1, :contents)::Bool
??? goto #3 if not %2
2 ? goto #4
3 ? Core.NewvarNode(:(counter))
??? counter
4 ? %7 = Core.getfield(%1, :contents)::Any
? %8 = (%7 + 1)::Any
? %9 = Core.getfield(#self#, :counter)::Core.Box
? Core.setfield!(%9, :contents, %8)
??? return %8
julia> @code_warntype c2()
Variables
c::Counter
Body::Int64
1 ? %1 = Base.getproperty(c, :counter)::Int64
? %2 = (%1 + 1)::Int64
? Base.setproperty!(c, :counter, %2)
??? return %2
Run Code Online (Sandbox Code Playgroud)
添加counter::Int = 0您的counterorc1定义将使其类型稳定,但无论如何您都会让 Julia 进行装箱/拆箱。所以总而言之c2,我通常会选择使用函子(版本)。或者,您可以c1通过使用这样的Ref包装器使您的(或)版本类型稳定:
julia> counter = let
local counter = Ref(0) # local variable
f() = counter[] += 1 # returned function
end
(::var"#f#1"{Base.RefValue{Int64}}) (generic function with 1 method)
julia> counter()
1
julia> counter()
2
julia> counter()
3
julia> @code_warntype counter()
Variables
#self#::var"#f#1"{Base.RefValue{Int64}}
Body::Int64
1 ? %1 = Core.getfield(#self#, :counter)::Base.RefValue{Int64}
? %2 = Base.getindex(%1)::Int64
? %3 = (%2 + 1)::Int64
? %4 = Core.getfield(#self#, :counter)::Base.RefValue{Int64}
? Base.setindex!(%4, %3)
??? return %3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
347 次 |
| 最近记录: |