function - 有没有办法在 julia 中深度复制函数?

标签 function copy julia

与标题差不多。如果我分配 g=f 或执行 g=deepcopy(f),结果是一样的:重新定义 f 将重新定义 g 也是。有没有办法让 g 成为 f 的独立副本?

julia> function f(x) x end
f (generic function with 1 method)

julia> f(1)
1

julia> g = deepcopy(f)
f (generic function with 1 method)

julia> g(1)
1

julia> function f(x) x+1 end
f (generic function with 1 method)

julia> f(1)
2

julia> g(1)
2

最佳答案

Julia 中的 AFAICT 函数被认为是位类型:

julia> f(x) = x
f (generic function with 1 method)

julia> isbitstype(typeof(f))
true

这意味着对它们的 deepcopy 是空操作。以下是 deepcopy 的定义:

function deepcopy(x)
    isbitstype(typeof(x)) && return x
    return deepcopy_internal(x, IdDict())::typeof(x)
end

这样做的原因是每个函数都有自己的类型(但它可以有很多方法)。

phipsgabler 提出的解决方案之所以有效,是因为每次定义匿名函数时,它都会获得自己的新类型。看这里:

julia> typeof(x -> x)
var"#1#2"

julia> typeof(x -> x)
var"#3#4"

julia> typeof(x -> x)
var"#5#6"

但这有一个缺点——每次你将一个新的匿名函数传递给另一个函数时,它都必须被编译,例如:

julia> @time map(x -> x, 1:2);
  0.024220 seconds (49.61 k allocations: 2.734 MiB)

julia> @time map(x -> x, 1:2);
  0.023754 seconds (48.25 k allocations: 2.530 MiB)

julia> @time map(x -> x, 1:2);
  0.023336 seconds (48.25 k allocations: 2.530 MiB)

对比

julia> fun = x -> x
#7 (generic function with 1 method)

julia> @time map(fun, 1:2);
  0.023459 seconds (48.23 k allocations: 2.530 MiB)

julia> @time map(fun, 1:2);
  0.000016 seconds (4 allocations: 192 bytes)

julia> @time map(fun, 1:2);
  0.000013 seconds (4 allocations: 192 bytes)

回到你原来的问题。即使你写这样的东西:

julia> f(x) = x
f (generic function with 1 method)

julia> g = x -> f(x)
#1 (generic function with 1 method)

julia> g(1)
1

你得到:

julia> f(x) = 2x
f (generic function with 1 method)

julia> g(1)
2

因为 f(x) = 2x 替换了函数 f 的方法,但它的类型没有改变(如上所述 - 一个函数可以有很多方法,你甚至可以更新函数的方法,如上例所示)。这与您解释过的所谓“世界时代”问题有关here在 Julia 手册中。

关于function - 有没有办法在 julia 中深度复制函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64855265/

相关文章:

PHP如何调用包含文件函数

julia - 从 Julia 中的离散分布中抽样

使用函数为矩阵赋值时 C 程序崩溃

javascript - 通过字符串名称调用 "local"函数而不使用 eval?

javascript - JS中复制到剪贴板

python - Python 如何建立对象之间的相等性?

matlab - 如何从 Julia 中的字典创建结构或类型?

dataframe - Julia:将函数应用于 DataFrame 中的每个单元格(不丢失列名)

swift - if 可选参数的 swift 函数中的条件

c++ - 如何修改给定的类以使用 const 运算符