ReplaceAll – Position of list arguments not displayed properly [closed]

This code

A[1, 2, 4, 5] /. A[a___] -> Position[{a}, 4]

return {}

Why this code not return 3 (a position of number 4) ?

I noticed that {a} is not evaluate to {1,2,3,4}. When we write this code as

A[1, 2, 4, 5] /. A[a___] -> Position[{a}, a]

return {1} (position of not evaluated letter a)

Is there a simple cure to this not evaluation problem.

=================

=================

1 Answer
1

=================

To “official-ize” my comments above, use RuleDelayed:

A[1, 2, 4, 5] /. A[a__] :> Position[{a}, 4]

{{3}}

The reason to use RuleDelayed here is the same as SetDelayed. They both keep the rhs unevaluated until the rule is used, meaning that once the pattern matches on the lhs, a__ is substituted in for a on the rhs. Otherwise with normal Rule, rhs is evaluated before a__ has the chance to be pattern matched.

And the example used by the OP maybe a toy example, but it is worth noting that Position works on heads other than List so

Position[A[1, 2, 4, 5], 4]

gives the same result.

  

 

Thank You :). RuleDelayed …this is exactly what i need.
– zbyneksmetana
Sep 29 ’15 at 14:11