Prev: Surface integral on a 3D region
Next: How export/recompile expressions and calculation code to run it
From: P. Fonseca on 29 Jul 2010 06:44 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? Regards, P. Fonseca
From: Andy Ross on 30 Jul 2010 06:56 On 7/29/2010 5:44 AM, 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? > > Regards, > P. Fonseca > I believe the following gives a clue... test[x_] := Module[{u}, Which[x == 0, 0, True, u[t_] := t^2;u[x]]] In[11]:= test[t] Out[11]= Which[t == 0, 0, True, u$612[t_] := t^2; u$612[t]] Since t == 0 doesn't explicitly evaluate to False, the entire Which remains unevaluated. You could use either of the following to ensure the first check always evaluates to either True or False. SameQ: In[12]:= test[x_] := Module[{u}, Which[x === 0, 0, True, u[t_] := t^2; u[x]]] In[13]:= test[t] Out[13]= t^2 TrueQ: In[14]:= test[x_] := Module[{u}, Which[TrueQ[x == 0], 0, True, u[t_] := t^2; u[x]]] In[15]:= test[t] Out[15]= t^2 -Andy
From: Szabolcs Horvát on 31 Jul 2010 02:39
[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 |