在朱莉娅(构图)中重复一个函数N次



我正在尝试创建一个函数,该函数本身组成函数f(x)N次,如下所示:

function CompositionN(f,N)
for i in 1:N
f(x) = f(f(x))
end
return f(x)

我需要函数 CompositionN 返回另一个函数,而不是值。

具有ntuple和喷溅的解决方案在一定数量的合成(例如 10 个)下效果非常好,然后从性能悬崖上掉下来。

另一种解决方案,使用reduce,对于大量组合来说速度很快,n,但对于小数量来说相对较慢:

compose_(f, n) = reduce(∘, ntuple(_ -> f, n))

我认为以下解决方案对于大型和小型n都是最佳的:

function compose(f, n)
function (x)  # <- this is syntax for an anonymous function
val = f(x)
for _ in 2:n
val = f(val)
end
return val
end
end

顺便说一句:在这里建议的方法中,组合函数的构造更快。生成的函数的运行时似乎是相同的。

您可以利用函数,它允许您组合多个函数:

julia> composition(f, n) = ∘(ntuple(_ -> f, n)...)
composition (generic function with 1 method)
julia> composition(sin, 3)(3.14)
0.001592651569876818
julia> sin(sin(sin(3.14)))
0.001592651569876818

这是一个递归方法:

julia> compose(f, n) = n <= 1 ? f : f ∘ compose(f, n-1)
compose (generic function with 1 method)
julia> compose(x -> 2x, 3)(1)
8

如果我们愿意做一点类型盗版,我们可以在函数上使用幂运算符^来表示n阶自组合:

julia> Base.:^(f::Union{Type,Function}, n::Integer) = n <= 1 ? f : f ∘ f^(n-1)
julia> f(x) = 2x
f (generic function with 1 method)
julia> (f^3)(1)
8

最新更新