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?




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

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


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

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

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

my_f = ExpensiveFunctor(eye(5,5), ones(5,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.