[Edit: See bottom for simple solution without Iterators, though I suggest using it and all the useful functions inside the package]
With Iterators package, the following could be a solution:
julia> using Iterators # install with Pkg.add("Iterators")
julia> reduce((x,y)->y,take(iterate(sqrt,11231.0),5))
1.791229164345863
iterate
does the composition logic (Do ?iterate
on the REPL for description). The newer version of Iterators (still untagged) has a function called nth
, which would make this even simpler:
nth(iterate(sqrt,11231.0),5)
As a side note, the (x,y)->y
anonymous function could nicely be defined with a name since it could potentially be used often with reduce
as in:
first(x,y) = x
second(x,y) = y
Now,
julia> reduce(second,take(iterate(sqrt,11231.0),5))
1.791229164345863
works. Also, without recursion (which entails stack allocation and waste), and allocation proportional to the depth of iteration, this could be more efficient, especially for higher iteration values than 5.
Without the Iterators package, a simple solution using foldl
is
julia> foldl((x,y)->sqrt(x),1:4, init=11231.0)
1.791229164345863
As before, the reduction operation is key, this time it applies sqrt
but ignores the iterator values which are only used to set the number of times the function is applied (perhaps a different iterator or vector than 1:4
could be used in the application for better readability of code)
repeatf(fn, x, n) = n == 1 ? fn(x) : repeatf(fn, fn(x), n-1)
– Suffruticose