在 Mathematica 中遇到默认值时有条件地转换表达式

Conditional transforming an expression when encountering default value in Mathematica

假设我有一个表达式x + x^2 + x^3,当x的幂小于它的最大幂时,我想用y替换x,下面是我在 Mathematica 中的代码:

x + x^2 + x^3 /. x^n_. /; n < 3 -> y^n

但结果是 y + y^2 + y^3 而不是 y + y^2 + x^3。我不知道我的错误在哪里。

你可以使用 Replace

Replace[x + x^2 + x^3, x^n_. /; n < 3 -> y^n, {1}]

levelspec {1} 将替换替换为模式为 Power[x, n] 的级别 1(除非 n 被省略)。如果替换是在级别 2,x 符号 inside Power 表达式被替换,n_. 默认值开始起作用。 ReplaceAll (/.) 影响所有级别,但是 Replace 和 levelspec {1} 完成工作。

如果没有 n_. 默认值,则需要额外的规则。

Replace[x + x^2 + x^3, {x^n_ /; n < 3 -> y^n, x -> y}, {1}]

反转主规则允许使用 ReplaceAll

x + x^2 + x^3 /. {x^n_ /; n >= 3 -> x^n, x -> y}

另一种方法是使用 Piecewise

Piecewise[{{y + y^2 + x^3, n < 3}}, x + x^2 + x^3]