marius311 / Memoization.jl

Easily and efficiently memoize any function, closure, or callable object in Julia.
MIT License
96 stars 2 forks source link

Allow to memoize a callable object #1

Closed dpsanders closed 4 years ago

dpsanders commented 4 years ago

I am trying to memoize a callable object, e.g.

struct MyObject
    f::Function
end

@memoize (x::MyObject)(n::Integer) = (x.f)(n)

But this doesn't seem to be implemented yet?

marius311 commented 4 years ago

Agreed, this would be cool to have, I will play with it, shouldn't be too hard.

marius311 commented 4 years ago

Also, this is probably obvious, but in your original case you can already memoize the inner function:

obj = MyObject(@memoize function foo(x) 
    println("Computed $x")
    x
end)

obj(3) # now memoized
marius311 commented 4 years ago

This should work now on the latest version (0.1.2).


using Memoization

struct MyObject
    f::Function
end

@memoize (x::MyObject)(n::Integer) = (x.f)(n)

f = MyObject(x->@show(x))

f(2)
f(2) # memoized

Different MyObject instances will all have their own individual memoization caches. Let me know if you run into any issues!