MathGroup Archive 2010

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

Search the Archive

Re: Behaviour of Replace

  • To: mathgroup at smc.vnet.net
  • Subject: [mg114895] Re: Behaviour of Replace
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Tue, 21 Dec 2010 00:22:35 -0500 (EST)
  • References: <201012200540.AAA22777@smc.vnet.net>

On 20 Dec 2010, at 06:40, Peter Breitfeld wrote:

>
> Suppose I have this nested list:
>
> demo = {1, {2, {3, {4, {5, {6, {7, {8, 8}}}}}}}}
>
> Replace[demo, {x_, y_} :> {x, a, y}, -1]
>
> Out={1, {2, a, {3, a, {4, a, {5, a, {6, a, {7, a, {8, a, 8}}}}}}}}
>
> I expected to have an a after the 1 too,

You shouldn't have.

Level[demo, -1]

=
{1,2,3,4,5,6,7,8,8,{8,8},{7,{8,8}},{6,{7,{8,8}}},{5,{6,{7,{8,8}}}},{4,{5,{6,{7,{8,8}}}}},{3,{4,{5,{6,{7,{8,8}}}}}},{2,{3,{4,{5,{6,{7,{8,8}}}}}}}}

These are all the subexpressions of demo at levels -1 to  -8. These are the subexpressions on which the replacement will be performed. Note that none of them has the form {1,x_} hence you should not have expected to get an a after the 1.


> what I tried to get using
>
> Replace[demo,{x_,y_}:>{x,a,y},-1,Heads->True]
>
> but this gives the same result as above.

Yes because

In[37]:= Level[demo,-1,Heads->True]
Out[37]= 
{List,1,List,2,List,3,List,4,List,5,List,6,List,7,List,8,8,{8,8},{7,{8,8}},{6,{7,{8,8}}},{5,{6,{7,{8,8}}}},{4,{5,{6,{7,{8,8}}}}},{3,{4,{5,{6,{7,{8,8}}}}}},{2,{3,{4,{5,{6,{7,{8,8}}}}}}}}

which does not add any more matches to the ones you had earlier

> But this will do what I wanted:
>
> Replace[demo, {x_, y_} :> {x, a, y}, {0, 8}]
>
> Out={1, a, {2, a, {3, a, {4, a, {5, a, {6, a, {7, a, {8, a, 8}}}}}}}}

Well, now you are acting on non-negaive levels. And

 Level[demo, {0, 8}]

=
{1,2,3,4,5,6,7,8,8,{8,8},{7,{8,8}},{6,{7,{8,8}}},{5,{6,{7,{8,8}}}},{4,{5,{6,{7,{8,8}}}}},{3,{4,{5,{6,{7,{8,8}}}}}},{2,{3,{4,{5,{6,{7,{8,8}}}}}}},{1,{2,{3,{4,{5,{6,{7,{8,8}}}}}}}}}

Look at the last element of this list. That's where your {1,a,..} comes from.

You could have got the same answer with puzzlement by using ReplaceRepeated

ReplaceRepeated[demo,{x_,y_}:>{x,a,y}]
{1,a,{2,a,{3,a,{4,a,{5,a,{6,a,{7,a,{8,a,8}}}}}}}}

Andrzej Kozlowski

>
> Can somone please explain this behaviour? What I found was that
>
> Level[demo,{0}] returns {{1},{2,{3...} beeing {demo}
>
> Thank you
> --
> _________________________________________________________________
> Peter Breitfeld, Bad Saulgau, Germany -- http://www.pBreitfeld.de
>



  • Prev by Date: Re: switching between versions 7 and 8
  • Next by Date: Re: Complete uninstall of Mathematica 6/7/8 on a Mac
  • Previous by thread: Behaviour of Replace
  • Next by thread: Counting