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

Eve*_*rez 5 mutable composition repeat function-composition julia

我正在尝试创建一个由函数 f(x) 组成 N 次的函数,类似于:

function CompositionN(f,N)
             for i in 1:N
                f(x) = f(f(x))
             end
return f(x)
Run Code Online (Sandbox Code Playgroud)

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

DNF*_*DNF 4

使用 splatting 的解决方案ntuple在达到一定数量的合成(例如 10 个)时效果非常好,然后就会出现性能悬崖。

\n

另一种解决方案是使用reduce,对于大量组合而言速度很快,n,但对于少量组合则相对较慢:

\n
compose_(f, n) = reduce(\xe2\x88\x98, ntuple(_ -> f, n))\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
function compose(f, n)\n    function (x)  # <- this is syntax for an anonymous function\n        val = f(x)\n        for _ in 2:n\n            val = f(val)\n        end\n        return val\n    end\nend\n
Run Code Online (Sandbox Code Playgroud)\n

顺便说一句:在此处建议的方法中,组合函数的构造速度更快。结果函数的运行时间似乎是相同的。

\n