The special syntax the uses Part and Set (e.g. c[["h"]] = i
) doesn't work for constants. So, for example, this doesn't work:
<|"s" -> "a", "v" -> 1, "h" -> 0, "n" -> 0, "x" -> 0|>[["s"]] = 1
Given your definition for setHome
:
setHome[c_, i_] := (c[["h"]] = i)
when you execute setHome[testCd, 5]
, this does NOT become testCd[["h"]]=1
. The expression setHome[testCd, 5]
immediately evaluates to setHome[<|"s" -> "a", "v" -> 1, "h" -> 0, "n" -> 0, "x" -> 0|>, 5]
, and thus we're applying Part/Set to a constant expression, not a symbol.
In your second example, Function has the HoldAll attribute, so nothing is getting executed in the body of the function until after the slot replacements have occurred. So in that case, we have Part/Set working on a symbol.
If you want, you can set the HoldAll attribute for setHome
(SetAttributes[setHome, HoldAll]
), and it should work (because testCd
won't immediately be evaluated, but will be inserted into the function definition as just the symbol testCd
).
Having said all of that, I would prefer using AssociateTo
anyway.