Message Boards Message Boards

0
|
1104 Views
|
2 Replies
|
1 Total Likes
View groups...
Share
Share this post:
GROUPS:

Pattern Substitution inside function

The following simple operator is not working:

tem1 = (q + Subscript[WOther, 1])
Z[w_] = tem1 /. { Subscript[WOther, 1] -> w_}
Z[3]

Rule::rhs: Pattern w_ appears on the right-hand side of rule Z[w_]->q+w_.
q + w_
q + Pattern[3, _]

I also tried using a module, but that is
creating a similar problem.  I suspect that the use of the
underscore variables as a parameter of the procedure is conflicted
with the underscore-pattern variable.

Dr. Laurence Leff  Associate Professor of Computer Science,
Western Illinois University, Macomb IL 61455  on sabbatical
POSTED BY: laurence leff
2 Replies
Posted 10 years ago
Also, if your intention is to create a function which, when passed an argument, returns Q+WOther after replacing WOther with the argument, then the w_ in the left side of the function definition is a pattern which matches any argument, and can be referred to by the name w in the function definition on the right hand side. Just like in the rule in my first response. So w is a named formal argument.

Below I do this and we see it works. But note that when "=" is used to assign the function definition to the function symbol, it causes the right hand side to be evaluated before the asignment is made. That works here, but is often not what is wanted. In the definition of ZZ, the use of ":=" is a deferred assignment. The right hand side is assigned without evaluation. (Therefore no "Out.")  Rather it is evaluated when the function is called, after first replacing the instances of the formal parameter(s) with the associated argument(s).

(Note that I eliminated the subscripting to make the code in the code box more readable. )

 In[1]:= tem1 = q + WOther;
 
 In[2]:= Z[w_] = tem1 /. WOther -> w
 
 Out[2]= q + w
 
 In[3]:= Z[something]
 
 Out[3]= q + something

In[4]:= ZZ[w_] := tem1 /. WOther -> w

In[5]:= ZZ[somethingElse]

Out[5]= q + somethingElse
POSTED BY: David Keith
Posted 10 years ago
Yes. The underscore is a reserved character. Mathematica allows it on the left side of a rule where is specifies a pattern, and can give a name to the matching object for use in the right side of the rule. But occuring on the right side, it is a syntax error.
In[1]:= {x, y} /. {a_, b_} -> {b, a}

Out[1]= {y, x}
Best,
David
POSTED BY: David Keith
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract