Skip to content

Instantly share code, notes, and snippets.

@axsk
Last active September 2, 2022 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axsk/2e27bb00e522cb865ad52040bfc3d341 to your computer and use it in GitHub Desktop.
Save axsk/2e27bb00e522cb865ad52040bfc3d341 to your computer and use it in GitHub Desktop.
cachedfunction.jl
# basically a type stable version of memoize.jl with a 1-element dict/cache
# it would be nice however to be able to only call cachedf = cache(f)
# such that cachedf would be typle stable.
# so far i have no idea how to achieve this
mutable struct CachedFunction{F, I, O}
f::F
in::I
out::O
end
cache(f, in...) = CachedFunction(f, in, f(in...))
function (cf::CachedFunction)(in...)
if (cf.in ≠ in)
cf.in = in
cf.out = cf.f(in...)
end
return cf.out
end
f(x) = (sleep(1); x*x) # f is generic
f_cached = cache(f, 0) # f_cached is no more generic :(
@time f_cached(0)
@time f_cached(1)
@time f_cached(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment