MathGroup Archive 2011

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

Search the Archive

Re: alternatives to MapIndexed?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg117849] Re: alternatives to MapIndexed?
  • From: Peter Pein <petsie at dordos.net>
  • Date: Fri, 1 Apr 2011 02:36:28 -0500 (EST)
  • References: <imshk8$5vm$1@smc.vnet.net>

Am 29.03.2011 14:00, schrieb Michael:
> Are there any alternatives to MapIndexed for determining where in an
> expression a sub-expression is?
>
> Specifically, I am trying to figure out a way to attach the depth of
> certain sub-expressions to those sub-expressions.  However, I want to
> ignore (or include only) certain heads in the calculation of depth.
>
> As an example:
>
> In[137]:= MapIndexed[({#2, #1})&,
>    F[a, b, F[x, y, G[v, F[q, r], w], z], c], Infinity]
>
> Out[137]= F[{{1}, a}, {{2}, b}, {{3},
>     F[{{3, 1}, x}, {{3, 2}, y}, {{3, 3},
>       G[{{3, 3, 1}, v}, {{3, 3, 2},
>         F[{{3, 3, 2, 1}, q}, {{3, 3, 2, 2}, r}]}, {{3, 3, 3}, w}]}, {{3,
>         4}, z}]}, {{4}, c}]
>
> What I would like is something that produces the output:
>
> F[{{1}, a}, {{2}, b}, {{3},
>     F[{{3, 1}, x}, {{3, 2}, y}, {{3, 3},
>       G[v, F[{{3, 3, 1}, q}, {{3, 3, 2}, r}]}, w]}, {{3,
>         4}, z}]}, {{4}, c}]
>
> i.e. in the above example only expressions with a head of F are counted
> (or those with G are excluded).
>
> An option to MapIndexed to include or exclude based on a pattern would
> be great, if it existed.
>
> I have found that I can kind of hack the solution using Length[Stack[]]
> but it appears to be computationally prohibitive to use this approach
> for large expressions.  All the other things I have thought up wind up
> causing uncontrolled recursion - Mathematica's approach to re-evaluating
> an expression until nothing changes seems to be a big stumbling block I
> have.  Perhaps there is an easy solution I am missing.
>
> Any suggestions?
>
> Thanks,
>
> Michael
>
I might have overlooked somthing due to the nested result but I think

In[1]:= expr=F[a,b,F[x,y,G[v,F[q,r],w],z],c]
Out[1]= F[a,b,F[x,y,G[v,F[q,r],w],z],c]
In[2]:= 
MapIndexed[{#2,#1}&,expr,\[Infinity]]//.G[x1___,{_List,var_},x2___]:>G[x1,var,x2]
Out[2]= 
F[{{1},a},{{2},b},{{3},F[{{3,1},x},{{3,2},y},{{3,3},G[v,F[{{3,3,2,1},q},{{3,3,2,2},r}],w]},{{3,4},z}]},{{4},c}]

should do what you want.

hth,
  Peter


  • Prev by Date: Re: why extending numbers by zeros instead of dropping precision is a good idea
  • Next by Date: Re: Subject: Re: Rational[a,b] vs Rational[1,2]
  • Previous by thread: Re: why extending numbers by zeros instead of dropping precision is a good idea
  • Next by thread: Re: Subject: Re: Rational[a,b] vs Rational[1,2]