Replace Function Example

Details

Action

Replace is the workhorse of algebraic expression editing. Algebraic expressions such as X*(Y-1) + fn(A,B,C) are represented internally as trees such as:

+

/ \

* FN

/ \ / \ \

X - A B C

/ \

Y 1

where the nodes are functions (if arithmetic then usually binary functions) and the children of nodes are arguments. This is represented in Lisp Prefix form as:

( + ( * X ( - Y 1)) (FN A B C) )

Now MathScript implements automatic normalization when certain symbolic operations are done, and in most cases, the normalization will handle most routine replacements such as the ones we'll be illustrating below. The following functions and commands automatically normalize their arguments:

d(expr) returns the normalized form of expr.

d(expr, x1, ..., xn) returns the normalized form of the partial derivative.

dif expr, x1, x2, ..., xn stores the normalized form of the partial derivative in Answer

simplify expr
stores normalized form of simplification in Answer

solve equation, var
stores normalized form of solution in Answer

output "/p" prints normalized expression in Math Edit Window

In general, if the normalized forms of expr1 and expr2 are equal, then expr1 is algebraically equivalent to expr2 in the obvious sense. Still, there are functional identities such as:

cos(?a + ?b) = cos(?a)*cos(?b) - sin(?a)*sin(?b) for which normalization, or even simplification, cannot determine equality. For example, the normalized form of the left hand side of the above equation is not equal to the normalized form of the right-hand side. Replace may be used to create rulesets, so that you may extend normalization to account for functional and other algebraic identities that MathScript's built-in normalization rules are not perspicuous enough to handle.

The form of Replace is:

Replace(Boolean, Query, Target,

list( Test1, Subst1), list(Test2, Subst2), ... , list(TestN,SubstN));

where

Boolean is True or False

Query is a match expression but must not be a single match variable.

Target is an Expression Object

TestI is a logical test (often containing match variables)

SubstI is an algebraic expression (often a match expression)

If Replace is to be used in a Book, you must first load "Algebra". You should also execute readlong, and set precision to 0.

Execute:

readlong;

precision 0;

load "algebra";

make variable ?a;

make variable ?b;

make variable ?c;

make drop1(L) replace(true, ?a*?b, L, list(?b==1, ?a), list(?a==1, ?b));

The function drop1 searches its argument for products of the type 1*x or y*1. If it finds any products in that form, it replaces them with x or y respectively.

Thus,

make u drop1(x*1 + sin(1*y))

causes u to be set to:

x+sin(y)

Now evaluate

make i (X+1) * (Y*1 + 1*Z) ;

Then the value of drop1(i) is:

(* (+ X 1) (+ Y Z))

That is, if written to a math edit window

Output "/v", drop1(i)

would print:

(x+1) * (y + z)