For reasons I won't go into here, I became curious about the what would happen should I make a query that applies PreIncrement
to one key in a list of associations. I admit that it could be argued that PreIncrement
should not be used in this way. In fact, because PreIncrement
is HoldFirst
and expects a symbol bound to a value, I was rather expecting Mathematica to complain about what I was about to do. I couldn't see how Mathematica was going to find such a symbol in the situation I was setting up.
The list of associations I will use is
assocs = {<|"a" -> 1, "b" -> 3|>, <|"a" -> 2, "b" -> 2|>, <|"a" -> 3, "b" -> 1|>};
and the query I will make is
Query[All, "b", PreIncrement] @ assocs
The first evaluation.
result = Query[All, "b", PreIncrement] @ assocs; {result, assocs}
{{4, 3, 2}, {<|"a" -> 1, "b" -> 3|>, <|"a" -> 2, "b" -> 2|>, <|"a" -> 3, "b" -> 1|>}}
Surprise. No complaints from Mathematica and the result seems reasonable. Now I'll do it a couple of more times.
result = Query[All, "b", PreIncrement] @ assocs; {result, assocs}
{{5, 4, 3}, {<|"a" -> 1, "b" -> 3|>, <|"a" -> 2, "b" -> 2|>, <|"a" -> 3, "b" -> 1|>}}
result = Query[All, "b", PreIncrement] @ assocs; {result, assocs}
{{6, 5, 4}, {<|"a" -> 1, "b" -> 3|>, <|"a" -> 2, "b" -> 2|>, <|"a" -> 3, "b" -> 1|>}}
This is very strange. I expected result
to have the same value after each evaluation. Since none of the associations in assocs
is modified by the query, what is PreIncrement
actually incrementing?
++assocs[[All, "b"]]
appears to work correctly. $\endgroup$ – Mr.Wizard May 21 '17 at 19:11Query
mechanism. The behavior you report is a simple effect of the associations inassocs
being destructively modified, so there is no mystery about where the incremented values are coming from. $\endgroup$ – m_goldberg May 21 '17 at 19:48Query
does not makes me think that the latter is a bug. $\endgroup$ – Mr.Wizard May 21 '17 at 19:52Query
is a big part of the issue. As toSlice
not being in a state of grace, I feel nervous about the way it's implemented. 1) Should it memoize? This thread seems to show that doing so can be dangerous (at least to anybody expecting functional behavior). 2) Can a function that depends on another function calledInternal`UnsafeQuietCheck
ever be fully trusted? $\endgroup$ – m_goldberg May 21 '17 at 20:08