MathGroup Archive 2000

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: string-variable-Set-snarl

  • To: mathgroup at smc.vnet.net
  • Subject: [mg22457] Re: [mg22491] string-variable-Set-snarl
  • From: Bojan Bistrovic <bojanb at python.physics.odu.edu>
  • Date: Wed, 8 Mar 2000 02:21:54 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

> Dear Advanced Mathematica Users,
> 
>  The following is a short and perhaps trivial problem that has caused me
> some frustration.  I cannot write a program that allows me to change the
> value of any given variable if given the name of the variable as a
> string.  What follows is an equivalent situation.  Let
> 
> In[3]=      {cow = Random[], emu = Random[], ant = Random[]}
> Out[3]=    {0.2, 0.3, 0.4}
> 
>        . . . . some selection process . . . .
> 
> In[25]=      animalname
> Out[25]=    cow
> 
> In[25]=     Head[animalname]
> Out[25]=   String
> 
> Given a string, here "cow", corresponding to a variable, here cow, I
> cannot clear or set a value for the variable itself.  Of course I cannot
> use Clear[cow] or cow = 2 because I do not know which variable will be
> chosen, as represented by the variable animalname.  My lame attempts
> such as Clear[animalname] or ToExpression[animalname] = 2 only fail to
> affect cow - it seems that I am caught trying to work on the wrong side
> of the equals sign (Set)!  My goal would be a line such as:
> 
> In[28]=      ToExpression[animalname]
> Out[28]=    2
> 
> which I think would imply that cow = 2 and has thus been affected.  Who
> can guide me from line 25 to line 28?  What are the general
> considerations?
> 
>    Sincerely,
>    James J. Fuite.
> 
> 

It's a bit tricky ; what you need is MakeExpression instead of ToExpression
since MakeExpression[animalname] returns HoldComplete[cow] where cow has a
head Symbol, not String. Now you have to Map the Set function inside the
HoldComplete and then remove the HoldComplete Head with ReleaseHold:

In[1]:= {cow = Random[], emu = Random[], ant = Random[]}
Out[1]= {0.2, 0.3, 0.4}

...

In[25]:= animalname
Out[25]= cow

In[26]:= Head[animalname]
Out[26]= String


In[27]:= ReleaseHold[Map[Function[arg1,arg1=2,{HoldFirst}],
	MakeExpression[animalname]]]
Out[27]= 2

Note that the "{HoldFirst}" part is necessary to prevent the left-hand side of
"arg1=2" being evaluated

In[28]:= animalname
Out[28]= cow

In[29]:= cow
Out[29]= 2

Bye, Bojan

--
---------------------------------------------------------------------
Bojan Bistrovic,                                      bojanb at jlab.org
Old Dominion University, Norfolk VA & Jefferson Lab, Newport News, VA
---------------------------------------------------------------------


  • Prev by Date: Re: export graphic to ps---trouble with fonts
  • Next by Date: Re: Simplifying Problems
  • Previous by thread: Re: string-variable-Set-snarl
  • Next by thread: Re: string-variable-Set-snarl