Optimization 朱莉娅-这真的是一个单例匿名函数吗?

Optimization 朱莉娅-这真的是一个单例匿名函数吗?,optimization,julia,Optimization,Julia,@code\u native test()表明它是,但它是吗 using FastAnonymous # By making this a generated function we should get only one instance # for a given type (singleton for each Value type) @generated function save2arr_gen{Value}(::Type{Value}) array = zeros(V

@code\u native test()
表明它是,但它是吗

using FastAnonymous

# By making this a generated function we should get only one instance 
# for a given type (singleton for each Value type)

@generated function save2arr_gen{Value}(::Type{Value})

    array = zeros(Value, 100)

    return @anon (t, v) -> begin
        array[t] = v
    end
end

这意味着无论调用了多少次
save2arr\u gen(Float64)
,都只为其生成了一个值(lambda函数)。

请参阅以下段落:

生成的函数体只执行一次(不是完全执行) 为true,请参见下面的注释)当 编译参数类型。之后,表达式从 第一次调用时生成的函数被重新用作 方法体

因此,在上面的示例中,
array=zero(Value,100)
仅对
Value
的每个值执行一次,之后每次调用
save2arr\u gen
都将为相同的
数组产生一个新的突变表达式

function test()
    save2arr = save2arr_gen(Float64)
    save2arr(1, 24.24)

    shouldAlsoBe_save2arr = save2arr_gen(Float64)
    shouldAlsoBe_save2arr(1, 100.0)

    @assert save2arr.array[1] == 100.0 # This checks out.
end