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– MarcoB Apr 24 '18 at 13:59f1andf2functions. – Jason B. Apr 24 '18 at 14:01SetandSetDelayed. However, I still don't get whyAssociation[]needs aSetDelayedinstead of aSet. – LBogaardt Apr 24 '18 at 14:36DownValues. Then look at the down values for your two approaches. Btw, your goal is still unclear to me. Mathematically, an association is a function. Is your goal really just to produce a new association where you change what one of the keys maps to? If so, why not just useAssociation, or if your preferAssociateToto modify the old association? – Alan Apr 24 '18 at 14:42Associationas constructor function andAssociationas head of an atomic association object. See (148074) for more discussion on this point. The solution suggested by @MarcoB addresses this ambiguity directly. – WReach Apr 25 '18 at 16:49