I am trying to get started with Macros. As a second challenge for me (see the first one here) I try to understand an easy way to cache interims values between functions. Let’s say I have two functions
function f(p,q,s) x = p*q; # or something much more challenging, time-consuming return (x*s)^2 # something easy end function g(p,q,t,v) x = p*q; #recompute - again time consuming return (x/t)^(1/v) # something easy end
such that both functions have an interims value
xdepending on both
p,q (in my case vectors, but for this example let’s say integers or floats). I would like to be able to
hook into both functions with a macro to cache
x, so maybe this is similar to Memoize.jl for which I couldn’t find a documentation.
What I would like to do is that a call like
@cache :f (:p,:q) f(p,q,s)
stores the computed
x in a dictionary (together with let’s say
f,p,q or that it was generated by
f with parameter values
p,q (the first two parameters).
(Note that my notation for macros and calling them as well as specifying f,p,q in the line might be completely of, since I am barely new to macros) in such a way that I can specify
'@cache [:f,:g] (:p,:q) g(p,p,t,v)
that can look up whether a value (namelyx
) was computed by eitherf
org` (I.e. the square brackets are a collections) by the same parameters with respect to p and q (hence the round brackets for a tuple, but it has to refer to the first two parameters) such that that value can be reused.
- my parameters are always ordered that way, so p is first q is second
- x will always be called x by convention (it is for example a determinant or a matrix from an singular value decomposition but always with a fixed meaning and hence fixed name consistent over both functions
- Of course if the first call already “finds” a value for (f,p,q) or (g,p,q) it would also reuse that one
Is that possible with macros or am I getting too exited here about macros?