I find the following behaviour deeply counter-intuitive:
<|1 -> 123.456 |> /. {x_?NumericQ -> Round[x]}
(* <|1 -> Round[123.456]|> *)
That is, if I make a rule-based replacement of things that sit as values inside an Association
object, and I require even a minimal amount of processing on the replacement, then it is just returned unevaluated.
Maybe I'm just completely getting associations wrong, but this is not at all the behaviour I expected. Instead, I would expect this to behave exactly like lists would do in this situation:
{1 -> 123.456} /. {x_?NumericQ -> Round[x]}
(* {1 -> 123} *)
Is this a bug? If not, what causes this behaviour? Is there some clean way to avoid it? I should note that if you copy <|1 -> Round[123.456]|>
into a blank cell and run that, it simplifies to <|1 -> 123|>
, but passing the result through Evaluate
doesn't do the same.
<|1 -> 123.456 |> /. {x_?NumericQ -> Round[x]}
Evaluate[%]
(* <|1 -> Round[123.456]|>
<|1 -> Round[123.456]|> *)
In case this is a bug, I'm running version 11.0.0 for Linux x86 (64-bit) (July 28, 2016), and I observe the same behaviour in version 10.4.1 for Linux x86 (64-bit) (April 11, 2016).
Answer
Association
is HoldAllComplete
. Once it is created, its parts will then normally be held unevaluated. Use RuleCondition
(or other options considered in this question) to force the r.h.s. of the rule to evaluate in-place:
<|1 -> 123.456|> /. {x_?NumericQ :> RuleCondition @ Round[x]}
(* <|1 -> 123|> *)
Note that when you enter
<|1 -> Round[123.456]|>
(* <|1 -> 123|> *)
the Round
function gets evaluated inside all right, because the evaluation here is inside a constructor, and it evaluates its arguments before constructing an association. But once it is constructed, no further evaluation can normally happen inside it (unless forced in some way, like e.g. the one I suggested above).
Comments
Post a Comment