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|>


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.

  • $\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$ Commented Jan 9, 2017 at 19:36
  • $\begingroup$ @SimonWoods, thanks, wasn't aware of that precedence rule. However, what about the underlying issue? $\endgroup$ Commented Jan 9, 2017 at 19:41
  • 3
    $\begingroup$ Another strongly related question, perhaps a dupe. $\endgroup$ Commented Jan 9, 2017 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$ Commented Jan 9, 2017 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$ Commented Jan 11, 2017 at 22:08


Browse other questions tagged or ask your own question.