The Mathematica Journal
Departments
Feature Articles
Tricks of the Trade
In and Out
Columns
New Products
New Publications
Classifieds
Calendar
Announcement
News Bulletins
New in the Library
Mailbox
FAQ
Contact Us
About the Journal
Staff and Contributors
Submissions
Subscriptions
Advertising
Back Issues
Home
Search
Download This Issue

Naming Parts of Expressions

Rules provide a mechanism for assigning names to parts of an expressions and then specifying what to do with some or all the names.

The notation year_ is a named pattern that designates a Mathematica expression. The rule {year_,debt_}->{year,Log[debt]} specifies that given a pair of values, Mathematica assigns the name year to the first element and debt to the second element in the pair, and returns the pair {year,Log[debt]}.

Actually, we didn't need to use this rule because there's a function for making log plots.

Let's look at some more examples of rules with named patterns.

Triples are replaced by pairs.

The rule swaps the elements in each pair.

The elements in a pair are swapped. There is only one pair in the expression.

Each pair gets replaced by another pair consisting of the first element and the log of the second element.

The largest (outermost) pair is replaced by another pair consisting of the first element and the log of the second element.

The symbol f is replaced by g.

Since the rule matches the entire expression, Mathematica replaces the head of the expression with g. It doesn't look deeper into the expression.

Mathematica repeatedly replaces f with g until the rule no longer applies.

Mathematica applies the rule to the subexpressions Log[x] and Log[y + Log[t]] and transforms them to x and y+Log[z+Log[t]]. The rule doesn't get applied to subexpressions of these expressions. Once a transformation is made, Mathematica doesn't apply the rule again, unless we use //. or ReplaceRepeated. So, the rule doesn't get applied to the nested calls to Log.


Copyright © 2002 Wolfram Media, Inc. All rights reserved.