在 Julia 中重复一个函数 N 次(组合)

Repeat a function N times in Julia (composition)

我正在尝试创建一个由函数 f(x) 本身组合 N 次的函数,类似这样的事情:

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

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

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

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

具有 ntuple 和 splatting 的解决方案在达到一定数量的组合(比如 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> 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 阶 self-composition:

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