Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In fact, <code>Replace</code> and <code>ReplaceAll</code> are <em>not</em> the same. You can think of <code>Replace</code> as a more precise version, since with <code>Replace</code> you can specify the levels in expression on which you want the replacements to happen. The difference here is somewhat similar to that between <code>Map</code> and <code>MapAll</code>, except the subtlety that <code>ReplaceAll</code> does not work depth-first (see below). Another difference, also rather subtle, is that <code>Replace</code> takes the <code>Heads</code> option, while <code>ReplaceAll</code> does not, which makes <code>Replace</code> yet more precise than <code>ReplaceAll</code>.</p> <p>By default, <code>Replace</code> works <em>only</em> at level 0, which is, entire expression. Your <code>z</code> is deeper however:</p> <pre><code>In[220]:= Clear[z] hz = z/(0.5 - 1.4 z + z^2); Position[hz, z] Out[222]= {{1}, {2, 1, 2, 2}, {2, 1, 3, 1}} </code></pre> <p>If you use the level specification for <code>Replace</code>, you can achieve an effect similar to, but not always the same as that of <code>ReplaceAll</code>:</p> <pre><code>In[223]:= Replace[hz,z-&gt;Exp[I*w],{0,Infinity}] Out[223]= E^(I w)/(0.5\[VeryThinSpace]-1.4 E^(I w)+E^(2 I w)) </code></pre> <p>The difference between <code>Replace</code> with lev.spec <code>{0,Infinity}</code> and <code>ReplaceAll</code> is that the former acts depth-first, sub-expressions before expressions, while the latter works from larger expressions to their parts. It is discussed in more detail e.g. <a href="http://www.mathprogramming-intro.org/book/node218.html" rel="nofollow noreferrer">here</a>. One example where this difference was used to one's advantage can be found in <a href="https://stackoverflow.com/questions/6562902/efficient-way-to-remove-empty-lists-from-lists/6563973#6563973">this</a> post.</p> <p>Coming back to default behavior of <code>Replace</code>, which operates on entire expression: it is very useful when you want to transform only the entire expression, but none of its parts (which may accidentally match the pattern in your rule). One example of such application of <code>Replace</code> is <a href="https://stackoverflow.com/questions/6234701/how-to-block-symbols-without-evaluating-them/6236264#6236264">here</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload