Search code examples
juliarepeatcompositionmutablefunction-composition

Repeat a function N times in Julia (composition)


I'm trying to make a function that compose a function f(x) by itself N times, something like that:

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

I need that the function CompositionN returns another function, not a value.


Solution

  • The solution with ntuple and splatting works very well up to a certain number of compositions, say 10, and then falls off a performance cliff.

    An alternative solution, using reduce, is fast for large numbers of compositions, n, but comparatively slow for small numbers:

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

    I think that the following solution is optimal for both large and small 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
    

    BTW: it is the construction of the composed function which is faster in the approach suggested here. The runtimes of the resulting functions seem to be identical.