COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### Nesting Pure Functions with more than one variable

• Email
• Follow

```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!!!

Ashraf

```
 0
Reply Elansary (2) 6/27/2003 10:45:33 AM

See related articles to this posting

```>-----Original Message-----
>From: Ashraf El Ansary [mailto:Elansary@btopenworld.com]
>Sent: Friday, June 27, 2003 12:31 PM
>To: mathgroup@smc.vnet.net
>Subject:  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!!!
>
>
>
>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}

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

```
 0
Reply Hartmut.Wolf (216) 6/28/2003 7:33:37 AM

1 Replies
44 Views

Similar Articles

12/6/2013 5:37:22 PM
page loaded in 56464 ms. (0)