Rob N
Rob N

Reputation: 16439

Why is this mathematica pattern variable not evaluated?

Apparently these pattern variables don't work like I'd expect. Here is a simple example:

In[264]  :=  1 /. x_ -> {x, f[x], ToString[x]}
Out[264] := {1, f[1], "x"}

Why is that last element "x" instead of "1". The following works as expected.

In[267]:= y = 2;
   ToString[y]
Out[268]= "2"

thanks,
Rob

Upvotes: 1

Views: 286

Answers (2)

Michael Pilat
Michael Pilat

Reputation: 6520

The right-hand side of the rule is being evaluated before the replacement occurs, so you need to use RuleDelayed (:>) instead of Rule (->):

In[1]:= 1 /. x_ :> {x, f[x], ToString[x]}

Out[1]= {1, f[1], "1"}

Rule and RuleDelayed are analogous to Set (=) and SetDelayed (:=).

HTH!

Upvotes: 4

Cascabel
Cascabel

Reputation: 497602

Try Trace[1 /. x_ -> {x, f[x], ToString[x]}]. I don't have access to mathematica at the moment, but I believe you'll see that the replacement, in particular ToString[x], is evaluated before the pattern is applied, so effectively you're doing 1 /. x_ -> {x, f[x], "x"}.

Upvotes: 3

Related Questions