Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Iterated functions in Julia
module IteratedFunctions
export IteratedFunction, iterated
struct IteratedFunction{F} <: Function
n::UInt # ensure non-negative
IteratedFunction(f, n::Integer) = IteratedFunction(f, UInt(n))
# make it callable
(itfun::IteratedFunction)(x) = foldl((y,_) -> itfun.f(y), 1:itfun.n; init=x)
iterated(f, n=1) = IteratedFunction(f, n)
# collapse nested iterations if possible (does not overflow)
function iterated(itfun::IteratedFunction, n::Int)
n = UInt(n)
n <= typemax(UInt) ÷ itfun.n ?
IteratedFunction(itfun.f, itfun.n * n) :
IteratedFunction(itfun, n)
# do this if you love a thrilling life
Base.:^(f::Function, n) = iterated(f, n)
end # module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment