2
$\begingroup$

This question already has an answer here:

This behavior of replacement rule seems inconsistent in Association. First, the baseline example works as intended:

{ data[{1, 2, 3}],  data[{3, 4}]} // 
 ReplaceAll[data[x_List] :> Length[x]] 

{3, 2}

But in Association

<|"a" -> {1, 2, 3}, "b" ->  {3, 4}|> //  ReplaceAll[x_List :> Length[x]] 

<|"a" -> Length[{1, 2, 3}], "b" -> Length[{3, 4}]|>

No problem with Map:

<|"a" -> data[{1, 2, 3}], "b" ->  data[{3, 4}]|> // ReplaceAll[data[x_List] :> x]  // Map[Length]

<|"a" -> 3, "b" -> 2|>

Is this behavior by design or a bug?

Note, as per comment by Simon Woods, explicit Evaluate on the right hand side of RuleDelayed has precedence over the replacement so can't be used as a workaround in ReplaceAll - however, it works externally:

<|"a" -> {1, 2, 3}, "b" ->  {3, 4}|> // 
  ReplaceAll[x_List :> Length[x]] // Map[Evaluate]

<|"a" -> 3, "b" -> 2|>

EDIT:

Following comments, and in Questions here and here and from WR support, HoldAllComplete causes this behavior.

Wouldn't it more appropriate if only the Keys were held? Keys are supposed to be treated Verbatim, not as patterns to be matched. But Values are intended to be transparent.

The current model introduces an inefficiency for deeply nested Associations: the need to (post)-Map Evaluate to Infinity to achieve the desired replacement.

Would appreciate feedback on this issue, and perhaps make the case to WR.

$\endgroup$

marked as duplicate by Mr.Wizard Jan 9 '17 at 20:24

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ When you put Evaluate@Length[x] on the RHS of RuleDelayed it evaluates before the pattern is matched, so x has no value. Hence Length[x]=0 and Head[x]=Symbol $\endgroup$ – Simon Woods Jan 9 '17 at 19:36
  • $\begingroup$ @SimonWoods, thanks, wasn't aware of that precedence rule. However, what about the underlying issue? $\endgroup$ – alancalvitti Jan 9 '17 at 19:41
  • 3
    $\begingroup$ Another strongly related question, perhaps a dupe. $\endgroup$ – Leonid Shifrin Jan 9 '17 at 20:11
  • 1
    $\begingroup$ @Kuba But it looks like various pieces of the full explanation has been scattered in all those questions we link here, while it would be nice to have a single larger canonical discussion of this and strongly related matters. $\endgroup$ – Leonid Shifrin Jan 9 '17 at 20:13
  • 1
    $\begingroup$ @LeonidShifrin, ps, WR support has filed a suggestion with devs on this issue - similar to what I wrote up in the EDIT - not that this means it will be handled, they're usually backlogged. $\endgroup$ – alancalvitti Jan 11 '17 at 22:08