# Mathematica/規則、模式、函數

## 規則與模式

### Rule、RuleDelayed、Replace、ReplaceAll

#### 基礎的規則和頭部Rule

``````In[]:= Clear[a, b, ourrule];
ourrule = a -> b
Out[]= a -> b```
```

``````In[]:= FullForm[ourrule]
Out[]= Rule[a, b]```
```

#### 如何應用規則：ReplaceAll

```我们定义的规则本身没有任何用处。Rule命令本身只是存储一条规则左值和右值的容器。Rule和引起表达式中规则替换的命令组合在一起才有用。
```

``````In[]:= Clear[f, a, b];
f[a] /. ourrule
Out[]= f[b]
(*或者这样*)
In[]:= f[a] /. a -> b
Out[]= f[b]```
```

``````In[]:= Clear[f, g, h];
f[a, g[a, h[a]]] /. a->b
Out[]= f[b, g[b, h[b]]]```
```

#### ReplaceAll在表達式上的嘗試順序

ReplaceAll對規則替換的嘗試通常從較大的表達式開始，如果在一個較大的表達式上匹配，便不會再嘗試其子表達式。當模式形如h[x_]時，匹配的順序就是這樣的。比如： ``` ```

``````In[]:= Clear[a, q];
{{{a}}}/.{x_}:>q[x]
Out[]= q[{{a}}]```

```
In[]:= {{{a}}} /. {x_} :> q[x] /. {x_} :> q[x]
Out[]= q[q[{a}]]
In[]:= {{{a}}} /. {x_} :> q[x] /. {x_} :> q[x] /.{x_} :> q[x]
Out[]= q[q[q[a]]]```
```

``````In[]:= {{{a}}} /. List -> q
Out[]= q[q[q[a]]]```
```

#### 規則的局部性

``````In[]:= f[a]
Out[]= f[a]```
```

``````In[]:= Clear[f];
{f[x], f[y], f[elephant], f[3]} /. f[z_] :> z^2
Out[]= {x2, y2, elephant2, 9}```
```

#### 延時規則 RuleDelayed函數

``````In[]:= RuleDelayed[a, b]
Out[]= a :> b```
```

#### Rule和RuleDelayed的區別

``````In[]:= Clear[sample, a, b, c, d, e, f, g, h];
sample = {d, e, a, c, a, b, f, a, a, e, g, a}```
```

``````In[]:= sample /. a -> Random[](*在最近的版本中，随机函数被替换为RandomReal和RandomInteger，详见帮助*)
Out[]= {d,e,0.746682,c,0.746682,b,f,0.746682,0.746682,e,g,0.746682}```
```

``````In[]:= sample /. a :> Random[]
Out[]= {d,e,0.16611,c,0.45842,b,f,0.144402,0.75737,e,g,0.515928}```
```

``````In[]:= n = 1;
sample /. a -> {a, n ++}
Out[]= {d, e, {a, 1}, c, {a, 1}, b, f, {a,1}, {a,1}, e, g, {a,1}}```
```

``````In[]:= n = 1;
sample /. a :> {a, n++}
Out[]= {d,e,{a,1},c,{a,2},b,f,{a,3},{a,4},e,g,{a,5}}
In[]:= Clear[sample, n];```
```

### 規則替換的有序性

#### 規則列表

``````In[]:= {a, b, c, d} /. {a -> 1, b ->2, d ->4}
Out[]= {1, 2, c, 4}```
```

``````In[]:= {a, b, c, d} /. {{a -> 1, b -> 2}, {c -> 3, d -> 4}}
Out[]= {{{1, 2, c, d}, {a, b, 3, 4}}}```
```

#### 有序性

``````
In[]:= Clear[a, f];
f[a] /. {a -> 5, a -> 6}
f[a] /. {a -> 6, a -> 5}
Out[]= f[5]
f[6]```
```

### 規則和計算過程之間的相互影響

#### 規則一應用，表達式就計算

```In[]:= Clear[a];
Gamma[a]
Out[]= Gamma[a]
```

```In[]:= Gamma[a] /. a -> 5
Out[]= 24
```

```In[]:= Gamma[a] /. a -> Pi
Out[]= Gamma[Pi]
```

```In[]:= Gamma[a] /. a -> N[Pi](*N是求数值结果用的*)
Out[]= 2.28804
```

#### 計算影響規則的可應用性

```In[]:= {f[Pi], Sin[Pi], Pi^2}
{f[Pi], Sin[Pi], Pi^2} /. Pi -> a
Out[]= {f[Pi], 0, Pi2}
{f[Pi], 0, a2}
```

```In[]:= ReplaceAll[{f[Pi], Sin[Pi], Pi^2}, Pi -> a]
Out[]= {f[a], 0, a^2}
```

```In[]:= Trace[{f[Pi], Sin[Pi], Pi^2} /. Pi -> a]
Out[]= {{{Sin[Pi],0},{f[Pi]],0,Pi^2}},{f[[Pi],0,Pi^2}/. Pi->a,{f[a],0,a^2}}
```

### 規則和簡單（非限制）模式

#### 一個簡單的規則和通用模式匹配策略

```In[]:= Blank[]
Out[]= _
```

```x^y * Sin[z]
```

```In[]:= Clear[a, x, y, z, g, h];
{x, Sin[x], x^2, x * y, g[y, x], h[x, y, z], Cos[y]} /. _ -> a
Out[]= a
```

```In[]:= FullForm[(_^_) * Sin[_]]
Out[]= Times[Power[Blank[], Blank[]], Sin[Blank[]]]
```

#### 檢查模式是否匹配：MatchQ函數

MatchQ，這是個非常有用的命令，它可以檢查一個給出的表達式是否和一個給出的模式匹配。它的第一個參數是一個表達式，第二個參數是一個模式，匹配時返回Ture否則返回False。比如：

```In[]:= MatchQ[x^y * Sin[z], (_^_) * Sin[_]]
Out[]= True
In[]:= MatchQ[Exp[-x^2]^2*Sin[Cos[x-y]^2], (_^_)*Sin[_]]
Out[]= Ture
In[]:= MatchQ[x*Sin[z], (_^_)*Sin[_]]
Out[]= False
```

#### 模式標籤（名稱）與表達式重構

```（base_^pwr_) * Sin[sinarg_]
```

```In[]:= {x^y*Sin[z], Exp[-x^2]^2*Sin[Cos[x-y]^2]} /. (base_^pwr_) * Sin[sinarg_] -> {base, pwr, sinarg}
Out[]= {{x, y, z}, {E, -2 x2, Cos[x-y]2}}
```

```In[]:= MatchQ[a^a, b_^b_]
Out[]= True
In[]:= MatchQ[a^c, b_^b_]
Out[]= False
```

#### 例子：擁有單一固定參數的任意函數

```Clear[f, x];
f_[x]
```

```Clear[x, y, z, g, h, a]
{x, Sin[x], x^2, x*y, x + y, g[y, x], h[x, y, z], Cos[y]}
```

```In[]:= {x, Sin[x], x^2, x*y, x + y, g[y, x], h[x, y, z], Cos[y]} /. {f_[x] -> f[10]}
Out[]= {x, Sin[10], x^2, x y, g[y, x], h[x, y, z], Cos[y]}
```

```In[]:= FullForm[{x, Sin[x], x^2, x*y, x + y, g[y, x], h[x, y, z], Cos[y]}]
Out[]= List[x, Sin[x], Power[x, 2], Times[x, y], Plus[x, y], g[y, x],
h[x, y, z], Cos[y]]
```

#### 首個參數固定的任意二參數函數

```In[]:= {x, Sin[x], x^2, x*y, x + y, g[y, x], h[x, y, z],
Cos[y]} /. {f_[x, z_] -> f[10, z]}
Out[]= {x, Sin[x], 100, 10 y, 10 + y, g[y, x], h[x, y, z], Cos[y]}
```

```In[]:= FullForm[f_[x, z_]]
Out[]= Pattern[f,Blank[]][x,Pattern[z,Blank[]]]
```

```In[]:= {x,Sin[x],x^2,x*y,x+y,g[y,x],h[x,y,z],Cos[y]}/. {f_[x,z_]->{{"f now"，f},{"z now",z}}}
Out[]= {x,Sin[x],{{f now ， Power},{z now,2}},{{f now ， Times},{z now,y}},{{f now ， Plus},{z now,y}},g[y,x],h[x,y,z],Cos[y]}
```

```In[]:= {x,Sin[x],x^2,x*y,x+y,g[y,x],h[x,y,z],Cos[y]}/. {f_[x,z_]->f[10,z],f_[z_,x]->f[z,10]}
Out[]= {x,Sin[x],100,10 y,10+y,g[y,10],h[x,y,z],Cos[y]}
```