ReplaceAll
is way overused, and it can very easily lead to unexpected results (or bugs in your code) because it replaces at all levels. In fact, the example you show is one of the most common errors stemming from the misuse of ReplaceAll
.
I recommend using ReplaceAll
only when you know you need it, except for algebraic replacements.
Otherwise, use Replace
:
Replace[{{1, "2"}, {2, "3"}}, {x_, _ } :> {x, "SOMETHING"}, {1}]
Make Replace
your default choice unless you know why you need ReplaceAll
, especially when developing packages (where robustness is a requirement).
Of course, when doing interactive work, a bit of sloppiness if forgivable :-) /.
is just shorter to type.
{{1, "2"}, {2, "3"}} /. {x_Integer, _String} :> {x, "SOMETHING"}
$\endgroup$/.
is much too tempting because it is short. People should always default toReplace
(or in some casesLookup
) and useReplaceAll
only for algebraic replacements (or when replacing at all levels is required). $\endgroup$/.
can often be used well given a little thought, and I find defaulting toReplace
a bit heavy handed. Of course there are cases whereReplace
is far superior, but in many other cases I would argue that a pattern restriction as J. M. offered is entirely adequate and not bad practice. Careless use of/.
is just that: carelessness, and IMHO baroque code is not a remedy for that. $\endgroup$Replace
instead ofReplaceAll
baroque. The shorthand/.
is a minor convenience only. I do sloppily use/.
when working interactively, but when writing code which is expected to be robust, it is a good idea to use defensive programming. Even the smartest programmer makes mistakes, or fails to see consequences sometimes. It is good practice to try to make our programs predictable and to reduce the chance of mistakes. $\endgroup$