Re: associate a parameter name with a string
- To: mathgroup at smc.vnet.net
- Subject: [mg75416] Re: associate a parameter name with a string
- From: Szabolcs <szhorvat at gmail.com>
- Date: Sun, 29 Apr 2007 03:10:44 -0400 (EDT)
- Organization: University of Bergen
- References: <f0v5ve$8td$1@smc.vnet.net>
luhao wrote: > Dear all, > I have groups of files and I'd like to call a function with each file and assign the result > to a parameter with similar name as the file. How can I do that? > > Here are what I tried. > > In[30]:= > Map[ToExpression[StringReplace[#,"_26.txt"->"phe"]]&,FileNames["fd*26.txt"]] > Out[30]= > {fd01001phe,fd01002phe,fd01003phe,fd01004phe,fd01005phe,fd01phe} > > In[31]:= > FileNames["fd*26.txt"] > Out[31]= > {fd01001_26.txt,fd01002_26.txt,fd01003_26.txt,fd01004_26.txt,fd01005_26.txt,\ > fd01_26.txt} > > In[32]:= > MapThread[#1=f[#2]&,{%30,%31}] > Set::write : Tag Slot in #1 is Protected. > Out[32]= > {f[fd01001_26.txt],f[fd01002_26.txt],f[fd01003_26.txt],f[fd01004_26.txt], > f[fd01005_26.txt],f[fd01_26.txt]} > > Any suggestions? > > Thanks, > Hao Hi Hao, The simplest solution to use a predefined function to do the assignment instead of the anonymous one: In[1]:= assigner[x_,y_] := x=f[y] The SetDelayed (the := operator) prevents x=f[y] from being evaluated before x and y are substituted with actual values. In[2]:= MapThread[assigner, {{a, b}, {x, y}}] Out[2]= {f[x], f[y]} In[3]:= a Out[3]= f[x] In[4]:= b Out[4]= f[y] An alternative is to use Hold to prevent the evaluation of #1=f[#2] : In[1]:= MapThread[Hold[#1=f[#2]] &, {{a, b}, {x, y}}] Out[1]= {Hold[a=f[x]], Hold[b=f[y]]} In[2]:= ReleaseHold[%] Out[2]= {f[x],f[y]} In[3]:= a Out[3]= f[x] In[4]:= b Out[4]= f[y]