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. – Leonid Shifrin Feb 07 '16 at 23:03AtomQon a association returnsTrue. – m_goldberg Feb 07 '16 at 23:12AtomQon a association returnsTrue- which is rather unfortunate, and this was done mostly to forbid pattern-matching inside associations like other expressions, and also to avoid makingAssociationexplicitlyHoldAllComplete. But I didn't mean this fact, but the other things you stated about mutability and in-place modifications. Associations are clearly not atomic for part extraction and modifications, despite returningTrueonAtomQ. – Leonid Shifrin Feb 07 '16 at 23:14Seton 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. – Leonid Shifrin Feb 07 '16 at 23:22Mapand similar functions work on assocs. – Leonid Shifrin Feb 07 '16 at 23:23