Re: Which inside Module causes problems with ReplaceAll
- To: mathgroup at smc.vnet.net
- Subject: [mg111398] Re: Which inside Module causes problems with ReplaceAll
- From: Szabolcs Horvát <szhorvat at gmail.com>
- Date: Sat, 31 Jul 2010 02:39:08 -0400 (EDT)
- References: <i2rm29$r6b$1@smc.vnet.net>
[note: message sent to comp.soft-sys.math.mathematica as well] On 2010.07.29. 12:44, P. Fonseca wrote: > Hi, > > Version 7.0.1 > > This works: > > In[7]:= test[x_]:=Module[{u}, > u[t_]:=t^2; > u[x]] > > In[8]:= test[t]/.t->3 > > Out[8]= 9 > > > > > This doesn't: > > In[9]:= test[x_]:=Module[{u}, > > Which[ > x==0,0, > > True, > u[t_]:=t^2; > u[x] > ] > ] > > In[10]:= test[t]/.t->3 > > During evaluation of In[10]:= Pattern::patvar: First element in > pattern Pattern[3,_] is not a valid pattern name.>> > Out[10]= u$670[3] > > > > What's going on? > The key to understanding what happens in cases like this is breaking down your expressions and looking at what each part evaluates to. If you evaluate test[t], you get something similar to Which[t == 0, 0, True, u$743[t_] := t^2; u$743[t]] This is because Which will only evaluate if the test inside it evaluates to either True or False, not something else. If you replace t in this expression, it gets replaced in t_ (full form: Pattern[t, _]) as well, leading to the nonsensical Pattern[3, _]. Hope this explains it, Szabolcs