Re: Question regarding procedures
- To: mathgroup at smc.vnet.net
- Subject: [mg63437] Re: Question regarding procedures
- From: "Jean-Marc Gulliet" <jeanmarc.gulliet at gmail.com>
- Date: Sat, 31 Dec 2005 06:40:35 -0500 (EST)
- Organization: The Open University, Milton Keynes, U.K.
- References: <dp2omp$8t6$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
"Dew 001" <dewdrops001 at gmail.com> a écrit dans le message de news: dp2omp$8t6$1 at smc.vnet.net... | | Hi, | I am relatively new to Mathematica and have the following question: | I created a procedure where the value of fitn_ comes from the user ... | | create [fitn_]:=Module[{func }, | func[{x_}]:=Evaluate[fitn]; | Print[func[{3}]]; | ] | | And called it with the following command: | create[x^2] | | I was hoping to get a 9 .. and if create[x^3] is entered I hoped to get back | 27. | | Any ideas? | | Thanks very much | | The problem you face is that the "x" in the definition of func has nothing to do with the "x's" entered by the user as argument of the function create. For instance, if you use an expression in, say, y and a replacement rule (y -> x) everything is fine as you can see below In[1]:= create[fitn_] := Module[{func}, func[{x_}] := fitn /. y -> x; Print[func[{3}]]; ] create[y^2] From In[1]:= 9 By the way, you do not need the *Evaluate* function since the definition of func is delayed and so will be evaluated each time a called is made. Now, how can you write a flexible definition for create that does not depend on the symbols used in the expression given as parameter? One way of accomplishing this is to use a second argument that holds the name of the variable. Note that the replacement rule has been modify accordingly. In[3]:= create2[fitn_, var_] := Module[{func}, func[{x_}] := fitn /. var -> x; Print[func[{3}]]; ] create2[x^3, x] From In[3]:= 27 Hope this helps, /J.M.