Generate a simple two-level association
In[1]:= m2 = <|"M" -> <|1 -> {1, 2, 3}, 2 -> {2, 3}|>, "F" -> <|1 -> {}, 2 -> {}|>|>
Out[1]= <|M-><|1->{1,2,3},2->{2,3}|>,F-><|1->{},2->{}|>|>
Show that m2["M"]
is an L-value (assignable) of type association
In[2]:= Head[m2["M"]]
Out[2]= Association
In[3]:= m2["M"] = <|1 -> {1}, 2 -> {1, 2}|>; m2
Out[3]= <|M-><|1->{1},2->{1,2}|>,F-><|1->{},2->{}|>|>
AssociateTo is HoldFirst
, it should pass m2["M"]
unevaluated to be treated as an L-value
In[4]:= Attributes[AssociateTo]
Out[4]= {HoldFirst, Protected}
In[5]:= AssociateTo[m2["M"], "b" -> 3]; m2
During evaluation of In[5]:= AssociateTo::rvalue: m2(M) is not a variable with a value, so its value cannot be changed. >>
Out[5]= <|M-><|1->{1},2->{1,2}|>,F-><|1->{},2->{}|>|>
I don't understand exactly why this fails. I am trying to do an in-place modification of the bottom level of a nested association. I was hoping to use the ideas of Use Scan
vs. Map
to accomplish this, but it appears that AssociateTo
is behaving in an unexpected way. Is there a way to accomplish this, perhaps using "Replacing parts of held expression?".
AssociateTo[m2[["M"]], "b" -> 3]; m2
. Strongly related discussion can be found here. $\endgroup$Set
on the top of this post, which works perfectly. Or many more examples, both in the docs and in my post I linked above. In my view, they are much closer to lists (arrays), than to complex numbers - they have similar mutability properties, and both are indexed containers of elements. $\endgroup$