Last active
April 10, 2021 18:07
-
-
Save FedericoStra/401469b50f2213dc2b37432a64cceba4 to your computer and use it in GitHub Desktop.
Iterated functions in Julia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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