Mathematica For Physicists - What is a Replacement Rule?

1. Pattern Matching

MatchQ[f[7],f[_]]

MatchQ[g[7],f[_]]

MatchQ[f[my[expression]],f[_]]

_ is an avatar for any expression

MatchQ[f[1,2,3,4,5],f[__]]

MatchQ[f[1,2,3,4,5],f[_]]

MatchQ[f[],f[__]]

MatchQ[f[],f[___]]

MatchQ[f[1,2,3,4,5,6,7],f[___]]

pattern=var1_[g[var2___]];

MatchQ[f[g[1]],pattern]

MatchQ[f[f[1]],pattern]

list={f[1],g[2],f[3],g[4]};

Cases[list,g[_]]

Cases[list,_g]

secondList={1,2,3,4,5,6};

Cases[secondList,_?EvenQ]

MatchQ[(3/4),((a_)/(b_))]

(3/4)//FullForm

MatchQ[(3/4),Rational[a_,b_]]

2. Applying Rules

ReplaceAll[f[a]+f[b],f[x_]->(x^2)]

f[a]+f[b]/.f[x_]->(x^2)

Differentiate (e^(-(x^2)+4x))Sin[x] at x=54

(D[(E^(-(x^2)+4x))Sin[x],x]/.x->54)//N

logExpand={Log[a_ b_]->Log[a]+Log[b], Log[((a_)^(k_))]->k Log[a]};

Log[(x^2)y]//.logExpand

soln=DSolve[y'[x]+2y[x]==((Sin[x])^2),y,x]

((y'[x]+2y[x]==((Sin[x])^2))/.soln[[1]])//Simplify

3. Conditions and Delayed Rules

sort={l___,x_,y_,r___}/;!OrderedQ[{x,y}]->{l,y,x,r};

exampleList={1,2,5,3,2,5,2,3,4,2,5};

exampleList//.sort

sort2={l___,x_,y_,r___}->{l,y,x,r}/;!OrderedQ[{x,y}];

exampleList//.sort2

list

list/.f[x_]->f[RandomReal[]]

list/.f[x_]:>f[RandomReal[]]

sort2={l___,x_,y_,r___}->{l,y,x,r}/;!OrderedQ[{x,y}];

exampleList/.sort2

sort3={l___,x_,y_,r___}:>{l,y,x,r}/;!OrderedQ[{x,y}];

exampleList//.sort3

f[1+2x+(x^2)]/.f[expr_]:>f[Simplify[expr]]

/. when RHS of rule is final value

:> when RHS of rule is some function you want to perform on matched pattern