Last active
September 2, 2022 11:02
-
-
Save axsk/2e27bb00e522cb865ad52040bfc3d341 to your computer and use it in GitHub Desktop.
cachedfunction.jl
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
# 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