Skip to content

Instantly share code, notes, and snippets.

@FedericoStra
Last active April 10, 2021 18:07
Show Gist options
  • Save FedericoStra/401469b50f2213dc2b37432a64cceba4 to your computer and use it in GitHub Desktop.
Save FedericoStra/401469b50f2213dc2b37432a64cceba4 to your computer and use it in GitHub Desktop.
Iterated functions in Julia
module IteratedFunctions
export IteratedFunction, iterated
struct IteratedFunction{F} <: Function
f::F
n::UInt # ensure non-negative
end
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)
end
# 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