I have an Association[]
which is the result of an intensive computation. Its values include the variable x
and I would like to turn the entire Association[]
into a set of Functions
.
I could use a Delayed Definition
(Reference) using the :=
function (SetDelayed
). However, this would redo the initial computation every time, which is inefficient. I prefer using an Immediate Definition
using =
for the Function
. However, that does not seem to work.
The following Mathematica code illustrates the problem:
f1[x_]=Association["linear"->x, "square"->x^2];
f1[3]["square"] (* x^2 *)
f2[x_]:=Association["linear"->x, "square"->x^2]
f2[3]["square"] (* 9 *)
Function f1 does not produce the desired result, whereas f2 does. How can I obtain the desired result? If possible, please explain the underlying theory, such that I will be able to tackle such problems myself in the future.
as = Association["key" -> x]; f3[xx_] := as /. x -> xx
$\endgroup$f1
andf2
functions. $\endgroup$Set
andSetDelayed
. However, I still don't get whyAssociation[]
needs aSetDelayed
instead of aSet
. $\endgroup$Association
as constructor function andAssociation
as head of an atomic association object. See (148074) for more discussion on this point. The solution suggested by @MarcoB addresses this ambiguity directly. $\endgroup$