Re: function mySet[]
- To: mathgroup at smc.vnet.net
- Subject: [mg36115] Re: [mg36096] function mySet[]
- From: Hartmut Wolf <hartmut_lebrecht_wolf at yahoo.com>
- Date: Thu, 22 Aug 2002 04:32:52 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
>-----Original Message----- >From: Prof. Korvink To: mathgroup at smc.vnet.net [mailto:korvink at informatik.uni-freiburg.de] >Sent: Wednesday, August 21, 2002 11:52 AM >Subject: [mg36115] [mg36096] function mySet[] > > >I am struggling with a problem: > >I would like to have a function mySet[] that takes a string argument >that is the correct string name of a "variable" and is able to >make assignments to that variable. Naively: > >a = { 1, 2, 3, 4, 5 }; >mySet[ s_String ] := > Symbol[ s ] = { 2, 3, 4, 5, 6 }; (* ERRONEOUS! *) >mySet[ SymbolName[ a ] ]; >a > >should give: > >{ 2, 3, 4, 5, 6 } > >The problem is that Symbol[ s ] immediately evaluates to a List >and I cannot for the love of anything generate an expression that >evaluates to the actual unevaluated symbol. >I have tried many variants with HoldAll and so on, with no luck, >hopefully only out of ignorance. > >What sometimes works (but circumstances is erratic!) is to do a: > >mySet[ s_String ] := > Evaluate[ToExpression[StringJoin[s,"={2,3,4,5,6}"]]] > >I do not find this a clean way to do things. Can anyone offer some >insight and perhaps a solution? > >Jan Korvink > > Jan, symbolizing "a" is of no avail, since we cannot stop evaluation when Symbol["a"] returns. Two solutions proposed: First, an idea which works always: build up the expression intended as a string outside the language, and then convert it to a Mathematica expression (i.e. compile and execute): In[9]:= strSet2[str_, expr_] := ToExpression[str <> "=" <> ToString[expr]] In[10]:= a = {1, 2, 3, 4, 5} Out[10]= {1, 2, 3, 4, 5} In[11]:= strSet2["a", {2, 3, 4, 5, 6}]; In[12]:= a Out[12]= {2, 3, 4, 5, 6} The second solution makes careful control of the execution: In[5]:= strSet[str_, expr_] := Function[sym, sym = expr, {HoldFirst}] @@ MakeExpression[str] In[6]:= a = {1, 2, 3, 4, 5} Out[6]= {1, 2, 3, 4, 5} In[7]:= strSet["a", {2, 3, 4, 5, 6}]; In[8]:= a Out[8]= {2, 3, 4, 5, 6} MakeExpression wraps its result into HoldAllComplete (so the generated symbol "a" wouldn't get evaluated), Apply a function with Hold attribute gets it directly to the lhs of Set, which is executed in turn. -- Hartmut Wolf __________________________________________________ Do You Yahoo!? HotJobs - Search Thousands of New Jobs http://www.hotjobs.com