How to define a function that remembers values?

I have a function that is very expensive to compute, fun(x). But I might be calling it on the same argument multiple times. Therefore it would be helpful if the function was able to store somehwere the result it obtained for a given value of x, instead of having to compute it again when it is called with the same value of x twice or more.

What is the best way to achieve this?

Yep.
https://github.com/simonster/Memoize.jl

2 Likes

Memoize, that’s the word I was looking for. Thanks.

  memoize(f) = 
    let d = Dict()
       (x...) -> get!(d, x, f(x...))
    end

Why not a simple functor in the form of a struct?

type ExpensiveFunctor{T<:AbstractFloat}
  x::Matrix{T}
  function (::Type{ExpensiveFunctor})(m1::Matrix, m2::Matrix)
    # expensive operations to initialize x
    new{promote_type(eltype(m1),eltype(m2))}(m1+m2)
  end

  function (m::ExpensiveFunctor){T<:Real}(x::AbstractVector{T})
    return m.x*x
  end
end

my_f = ExpensiveFunctor(eye(5,5), ones(5,5))
my_f(rand(1:10,5))

Memoization and precomputation have different purposes. You memoize a function if the arguments are not necessarily known in advance (or you don’t want to bother thinking about them), while precomputation helps you when a calculation can be broken down to stages, and one of these stages is reusable (and expensive). In some contexts, both are helpful.

2 Likes