RE: Nesting Pure Functions with more than one variable
- To: mathgroup at smc.vnet.net
- Subject: [mg42316] RE: [mg42295] Nesting Pure Functions with more than one variable
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Sat, 28 Jun 2003 03:22:03 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
>-----Original Message----- >From: Ashraf El Ansary [mailto:Elansary at btopenworld.com] To: mathgroup at smc.vnet.net >Sent: Friday, June 27, 2003 12:31 PM >To: mathgroup at smc.vnet.net >Subject: [mg42316] [mg42295] Nesting Pure Functions with more than one variable > > >Dear all, >I'm looking for a way to nest a pure function with more than >one variable. >For Example, > >In[1]:= >a={1,2,3}; >b={5,6,7}; >c:=Insert[#1,b[[#2]],#2+#2]& > > >This is what I'm trying to achieve [i.e to rearrange the above lists to >merge them together in a certain way], c[a,1] >c[%,2] >c[%,3] > >Out[4]= >{1,5,2,3} >Out[5]= >{1,5,2,6,3} >Out[6]= >{1,5,2,6,3,7} >I'm more interested in the concept of making a loop [or >nesting a function] >than achieving the end result. > >I'd assume that I'd need to nest c in a such way that my starting point >would be >#1=a , #2 = 1 then nest the result several times while >increasing #2 by one >increment each time > >Any idea!!! > >Your help is extremely appreciated > > >Ashraf > > What you want, is it something to the like In[1]:= a = {1, 2, 3}; b = {5, 6, 7}; In[5]:= Transpose[{a, b}] // Flatten Out[5]= {1, 5, 2, 6, 3, 7} 'zipping' the lists? ---------------------------------- The idiom you were looking for possible is: In[16]:= c := Insert[#1, b[[#2]], #2 + #2] & In[18]:= Fold[c, a, Range[3]] Out[18]= {1, 5, 2, 6, 3, 7} Or playing with your idea: In[20]:= s = a; MapIndexed[(s = Insert[s, #1, 2{#2}]) &, b]; s Out[20]= {1, 5, 2, 6, 3, 7} I recommend neither; but let's play further In[22]:= Module[{s=a}, MapIndexed[(s=Insert[s,#1,2{#2}])&,b]//Last] Out[22]= {1,5,2,6,3,7} then further (avoiding Insert) In[26]:= MapIndexed[{a[[#2]], #1} &, b] // Flatten Out[26]= {1, 5, 2, 6, 3, 7} ok, let's treat a and b on equal footing In[28]:= Map[{a[[#]], b[[#]]} &, Range[Length[a]]] // Flatten Out[28]= {1, 5, 2, 6, 3, 7} So we have found our own implementation for Transpose. -- Hartmut Wolf