1. Replacements and Patterns

Basic examples
Basically, replacement works like

x/.x->y

The x -> y part is called “rule”, /. is a shortcut for the command MouseOver[expression, rules].

ReplaceAll[x,x->y]

You can do replacements with any type of expressions, e.g. with functions.

(Sqrt[x])BesselK[((x^2)/2),1]+x Sin[x]/.Sin->Cos

Or with patterns (meaning, “everything that looks like...”)

((Sin[x/2]Sinh[y])/(Sin[x/2]Cosh[y]+Cos[x/2]Sinh[y]))/.Sin[p_]->Sin[2p]

By the way, it’s convenient to correct mistakes. It is similar to “Find all -> Replace with” structure.
You can use more than one replacement in one “/.”

((Sin[x/2]Sinh[y])/(Sin[x/2]Cosh[y]+Cos[x/2]Sinh[y]))/.{Sin[p_]->Sin[2p],Cos[p_]->Cos[2p]}

Also, you can use an array of replacements.

x/.{{x->3},{x->4},{x->5}}

Primary usage of that feature looks like this:

x/.Solve[(x^2)+1==0,x]

Solve and many other “solving” functions return sets of rules. We’ll talk about it later.

Now, let’s talk about problems. Consider the following example. What is the result of compilation?

2x/.{x->a,2x->b}

This result may seem counterintuitive. Going from left to right, we should change x to a and get 2a, with the second rule having no effect, right?.. Obviously, wrong. To understand, why, we need to look at expression from the Mathematica point of view.

Expression trees

2x//TreeForm

That structure is known as “expression tree”. It’s exactly what it says on the label - the tree representation of expression. Expressions as humans write them are nontrivial. They contain brackets, the order of evaluating operators is not linear (2+2*2), operators and variables are everywhere... Mess. On the other hand, trees are quite convenient for machines. I won’t go into the advantages here, you can always read about it or just write some simple calculator.
The root of the tree is an operation you will compute LAST. Operators have children: the numbers they are acting at, and “number” can be another operator.Consequently,one should evaluate such a tree from the leaves up to the root; programmatically, one will have a recursive function “evaluate”, which will be applied to the root and will call itself whenever child of the operator is operator itself.

2x y + 6-Sin[x]/(3 y)//TreeForm

Important notes to self: Plus and Times can have many arguments; division is represented as taking minus first power of whatever; minus is represented as Plus (Times -1).

Some examples here; any expression can be expanded into tree, do it.

Mathematica applies (something like) the algorithm below to the root of the tree.
1) Take the element of the tree. Check rules, left to right, to see if there’s one that coincides with some subtree of the tree that grows from that element. 
1.1) If found:
	2) stop checking 
	3) make replacement 
	4) apply 1) to anything that goes down from the replaced part.
1.2) If not found:
	5) apply 1) to every child of the root

And now we need many, many examples.

2x/.{x->a,2x->b}

The root element is Times, it has to children, 2 and x. Checking x: x is not Times, continue. Checking Times-2-x: it coincides with the tree, apply rule 2x -> b.

Sin[Sin[x]]/.Sin->Cos

The root element is Sin; checking the only rule, applying it. Then, continue to the children of changed expression. There’ll be one more Sin, rule applied, and x, nothing done.

2 Sin[x]/. 2 Sin->Cos

Not an easy one. 2 has no children, Sin has child x, so it’s impossible to understand how many child should Cos from the rule have. In that case, nothing is done.

Sin[x]Cos[x]/.Sin Cos->Tan

x may seem the same in Sin and Cos, but it’s two different leaves in the tree, so that case is similar to the previous. You could do it with

(2Sin)[x]/. 2Sin->Cos

But that’s absolutely useless, since one operator (2 Sin) is not Sin doubled. Mathematica doesn’t know what to do with it.

(2Sin)[5]//N

Now, there was recursion in the algorithms. Let’s consider one of the “basic examples”

(Sqrt[x])BesselK[((x^2)/2),1]+x Sin[x]//TreeForm

(Sqrt[x])BesselK[((x^2)/2),1]+x Sin[x]/.x->y

Is Plus equal to x? No. Check it’s children. Is either of Times equal to x? No. Check their children. Their we can see Sin, Power, BesselK and x. Apply rule to x and check all the children of operators. That way it will go down to all the leaves, changing every x to y.

Now, there was some talk about the subtrees. The reason is that some operators don’t have definite number of arguments. Consider Plus.

3+x+y/. 3+x->a

Despite the fact that Plus of 3+x+y has three children, and Plus of 3+x - only two, the rule is applied, and the subtree that matched to the lhs of the rule was changed. Complication with this approach is that Mathematica doesn’t try to apply the rule to the children which were NOT changed. I mean,

3+x+Sin[3+x]/. 3+x->a

As you can see, the second 3+x wasn’t changed just because the operator it connected to was partially changed. I think that it’s wrong approach, but I don’t write the rules.
You can overcome this obstacle by using ReplaceRepeated, or //.

3+x+Sin[3+x]//. 3+x->a

ReplaceRepeated[3+x+Sin[3+x], 3+x->a]

Living up to it’s name, ReplaceRepeated process the whole tree, and if it has applied the rule at least once, it returns to the root of the tree and starts again. Yeah, I know, everyone wants to see StackOverflow.

x//.{x->y,y->x}

That should be every creepy feature of MouseOver. Anyway, it’s everything I was able to find, and I’m pretty good at finding creepy features.
Since there are MouseOver and MouseOver, it seems possible there’s just MouseOver. Unfortunately, there’s. No shortcut for that one, it’s way too TreeForm-dependent to be frequently used.

Replace[x,x->a]

Replace[1+x,x->a]

Replace in the basic form only tries to apply rules to the root of the tree.
But it has third argument, called levelspec in docs. Rules will be applied to the level of the tree number levelspec, the third argument. The root has level 0.

Replace[1+x,x->a,1]

Replace[1+x,x->a,0]

It has it’s uses, but first we need to talk about patterns and conditions.

Patterns and conditions.

Before, I said that a pattern is “anything”. Now I would like to say “any subtree”. Or even “maximal subtree”, since Mathematica will always try to find maximal subtree. Entering p_, you allow Mathematica to put any subtree in place of p. She will use that allowance quite freely.

(Sqrt[x])BesselK[((x^2)/2),1]+x Sin[x]/.x_->a

Yeah. Mathematica starts from the root and seeks for subtree... Whole tree is a perfect candidate. So the whole expression just became x and was changed to a.
In basic examples there’s a good example of using patterns by themselves.

((Sin[x/2]Sinh[y])/(Sin[x/3]Cosh[y]+Cos[x/2]Sinh[y]))/.{Sin[p_]->Sin[2p],Cos[p_]->Cos[2p]}

Multiply all arguments of trigonometric functions by two? Easy. Here, Mathematica seeks a node with Sin or Cos and names p the subtree that grows from such node. Makes sense.

But patterns have one more convenient feature. Conditions.

{1, 123,-24,14,5}/.x_/;OddQ[x]->0

/;, aka Condition, is a condition on a pattern. Rule is applied only if condition is satisfied. In the example above I changed every odd quantity to zero. I could also use many logical expressions

{1, 123,-24,14,5}/.x_/;OddQ[x]||x>0->0

A little more useful usage - setting every symbolic quantity to zero. Function NumericQ (numeric quantity) checks whether its argument is a number, so...

2π+(x^2)+25(owl^37)+(y^3)/.x_/;Not[NumericQ[x]]->0

Oh, wait. I wanted 2π. But since Mathematica firstly used the whole expression as x, and it’s not numeric, it all became zero...
For polynomials, one can use

Replace[2π+(x^2)+25(owl^37)+(y^3),x_/;Not[NumericQ[x]]->0,1]

Replace only uses rule on the first level of the tree, on each of the addends. Hence you got the only term that’s numeric quantity.
Doing it in general case is... interesting exercise.
The same way you can cut the series, or leave out odd powers.

1+x+((x^2)/2)+((x^3)/6)+((x^4)/24)+((x^5)/120)+((x^6)/720)+((x^7)/5040)+((x^8)/40320)+((x^9)/362880)+((x^10)/3628800)/.x^n_/;n>4->0

1+x+((x^2)/2)+((x^3)/6)+((x^4)/24)+((x^5)/120)+((x^6)/720)+((x^7)/5040)+((x^8)/40320)+((x^9)/362880)+((x^10)/3628800)/.x^n_/;EvenQ[n]->0

(OddQ won’t work as expected, though. Why?)

Some fun, some usage

I really hope that I gave you either a strong understanding of replacements, or as strong a motivation to not use them in your workflow. First is cool, second is Ok, at least you won’t be stuck debugging some complicated undebuggable replacement.

I usually use them for symbolic -> numeric conversion.

((Sin[x/2]Sinh[y])/(Sin[x/3]Cosh[y]+Cos[x/2]Sinh[y]))/.{x->Pi,y->Pi/2}//N

I’m too lazy to define functions, replacements work just fine in such setting.

As I already mentioned, everything solving returns results in form of replacements. Unexpectedly, sometimes it’s really convenient. The following is easier than Map usage.

ListPlot[{Re[x],Im[x]}/.Solve[(x^10)+(x^2)+1==0,x],AspectRatio->1,PlotStyle->PointSize[Large]]

A-and... Replacements can do quite powerful things. Two rules all in all to transform any logarithmic expression into expanded form. Or into one Log.

logExpandRules={Log[x_ y_]->Log[x]+Log[y],Log[((x_)^(y_))]->y Log[x]};
Log[5(x^2)]+Log[10 x (y^(-1/2))]//.logExpandRules

logFactorRules={Log[x_]+Log[y_]->Log[x y],y_ Log[x_]->Log[(x^y)]};
Log[5(x^2)]+2Log[10 x (y^(-1/2))]//.logFactorRules

Exercises

Exercise 1.1

Here is a very simple expression that suffers numerous replacements. Don’t let it suffer alone, try to predict the result, check it and explain. Understanding of the tree form of the expressions is necessary.

Hold[2(x^2)]/.{2x->a x,(x^2)->b}

Hold[2(x^2)]/.{2x_->a x,(x^2)->b}

Hold[(((2x))^2)]//.{2x_->a x,x_ y_->b}

(((2x))^2)/.{2x_->a x,x_ y_->b}

If you’re doing the exercises in class, be sure to check your explanations with one of the teachers. You could get right answers with wrong methods, and it may prevent you from completing other exercises.

Exercise 1.2

But what about Times and Plus with indefinite number of children? Explain the results of computations.

Hold[2x 2x]/. 2x->a

x+y+z/.x_+y_->x y

Exercise 1.3

And these two are just plainly cruel.

Hold[2((x )^(2x))2x]/.{x->a,2x->b}

Hold[2((x )^(2x))2(x^(2x))]/.{x->a,2x->b}

Exercise 1.4

Create a set of rules that will expand linear function f. For example, f [3x + 2y] should become 3 f[x] + 2 f[y].

linearExpansion={None}

Problem 1.1

Construct a MouseOver that prefers ((Sin[x])^n) and ((Cos[x])^n) instead of Sin[nx] and Cos[nx].
MouseOver Cos[4x] using it.

Problem 1.2

Create a function with the same functionality as MouseOver, using replacements.

myCoefficient[expr_,form_]:=

Problem 1.3

Create a function with the same functionality as MouseOver. Use only replacements.

myApply[expr_]:=

Problem 1.4

Using only function MouseOver, replacements and pure functions, define the function with MouseOver functionality. It’s OK if your map acts only on lists.

myMap[func_,array_]:=Fold[...,array]