Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: Programatically creating delayed assignment

  • To: mathgroup at smc.vnet.net
  • Subject: [mg110228] Re: Programatically creating delayed assignment
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Wed, 9 Jun 2010 07:20:56 -0400 (EDT)

Hi Stuart,

Your code will not work as posted, because SetDelayed does not normally
evaluate any of its arguments. Therefore, you have to force it to, for
example by using explicit Evaluate. Here is a possibility:

Clear[assignElements];
assignElements[name_String, elemName_String, length_Integer] :=
  Module[{heldName = ToExpression[name, InputForm, Hold]},
   Clear @@ heldName;
   Evaluate[First@heldName] :=
    Evaluate[Table[ToExpression[name <> elemName][i], {i, length}]]];

Note that I added a line to clear possible previous definitions that a
symbol
in question may have. If you don't do this you may get some pretty insidious
bugs when using the function several times on the same symbol.

Here is how you can use it:

Scan[assignElements[#, "element", 3] &, {"a", "b"}]

?a

Global`a

a:={aelement[1],aelement[2],aelement[3]}

?b

Global`b

b:={belement[1],belement[2],belement[3]}

Hope this helps.

Regards,
Leonid





On Tue, Jun 8, 2010 at 3:06 PM, Stuart Nettleton <
Stuart.Nettleton at uts.edu.au> wrote:

> Hi, I would appreciate any thoughts regarding the programatic construction
> of delayed assignments, for example using something like the following
> Scan:
> Scan[(ToExpression[#]:= Table[ToExpression[# <> "element"][i], {i,
> 3}])&,{"a","b"}]
> to create the following delayed assignments:
> a:= {aelement[1], aelement[2], aelement[3]};
> b:= {belement[1], belement[2], belement[3]};
> Many thanks, Stuart
>
> --
> UTS CRICOS Provider Code:  00099F
> DISCLAIMER: This email message and any accompanying attachments may contain
> confidential information.  If you are not the intended recipient, do not
> read, use, disseminate, distribute or copy this message or attachments.  If
> you have received this message in error, please notify the sender
> immediately and delete this message. Any views expressed in this message
> are those of the individual sender, except where the sender expressly, and
> with authority, states them to be the views the University of Technology,
> Sydney. Before opening any attachments, please check them for viruses and
> defects.
>
>


  • Prev by Date: Re: Eliminating vertical lines in piecewise plot
  • Next by Date: Re: Simplifying complicated expressions
  • Previous by thread: Re: Programatically creating delayed
  • Next by thread: Re: Manipulate Plot command - blank plot