MathGroup Archive 2000

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

Search the Archive

Re: string-variable-Set-snarl

  • To: mathgroup at smc.vnet.net
  • Subject: [mg22526] Re: string-variable-Set-snarl
  • From: "Allan Hayes" <hay at haystack.demon.co.uk>
  • Date: Thu, 9 Mar 2000 03:24:16 -0500 (EST)
  • References: <89qhdg$amm@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

James and Tania,

After reading the replies of  Bojan Bistrovic and Hartmut Wolf I came up
with the following

Attributes[SetByNameOrSymbol] = HoldAll;

SetByNameOrSymbol[s_String, val_] :=
  (# = val) &[Unevaluated @@ MakeExpression[ s]]

SetByNameOrSymbol[s_, val_] := s = val

Tests:

SetByNameOrSymbol["cow", 2]; cow

        2

SetByNameOrSymbol[cow, 3]; cow

        3

SetByNameOrSymbol["cow", cow + 2]; cow

        5

If we have allow

animal = "cow";

Then the following will work

SetByNameOrSymbol[Evaluate[animal], 1]; cow

1

Allan
---------------------
Allan Hayes
Mathematica Training and Consulting
Leicester UK
www.haystack.demon.co.uk
hay at haystack.demon.co.uk
Voice: +44 (0)116 271 4198
Fax: +44 (0)870 164 0565



"James Fuite and Tania Nordli" <jfuite at ualberta.ca> wrote in message
news:89qhdg$amm at smc.vnet.net...
> 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.
>
>




  • Prev by Date: Re: Problem with Integration
  • Next by Date: Re: Error in Subtraction with V4.0??
  • Previous by thread: Re: string-variable-Set-snarl
  • Next by thread: Help