MathGroup Archive 2010

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

Search the Archive

Re: need something like ReplaceAllIndexed[]

  • To: mathgroup at smc.vnet.net
  • Subject: [mg108482] Re: need something like ReplaceAllIndexed[]
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Fri, 19 Mar 2010 06:45:42 -0500 (EST)
  • References: <201003190746.CAA08417@smc.vnet.net>

Hi Roger,

I am not sure if I understood correclty what you want, but you can use the
following

In[2]:= Clear[replaceLeaves];
replaceLeaves[expr_, lst_List] /;
   Length[Level[expr, {-1}]] == Length[lst] :=
  Module[{n = 1}, MapIndexed[lst[[n++]] &, expr, {-1}]];

to replace all leaves in your expression, in the order corresponding to a
depth-first traversal of an expression,  by consecutive elements of another
list. For instance,

In[4]:= replaceLeaves[b[a[c], a[c], a[d]], {e, f, g}]

Out[4]= b[a[e], a[f], a[g]]

Here is another alternative:

Clear[replaceLeavesAlt];
replaceLeavesAlt[expr_, lst_List] /;
  Length[Level[expr, {-1}]] == Length[lst] :=
 ReplacePart[expr, lst,
  Position[expr, _, {-1}, Heads -> False], List /@ Range[Length[lst]]]

In[11]:= replaceLeavesAlt[b[a[c], a[c], a[d]], {e, f, g}]

Out[11]= b[a[e], a[f], a[g]]


Regards,
Leonid



On Fri, Mar 19, 2010 at 10:46 AM, divisor <congruentialuminaire at yahoo.com>wrote:

> Hello mathGroup:
>
> I have an expression like this:
>
> b[ a[c], a[c], a[d]]
>
> a list like this:
>
> {e,f,g}
>
> I want to end up with
>
> b[ a[e], a[f], a[g]]
>
> I think of this as interleaving a list into an expression, but all my
> tries with ./,.//,MapIndexed[],MapAt[], Partition[Riffle[]] have come
> to no avail.
>
> Any help on this is greatly appreciated.
>
> Roger Williams
> Franklin Laboratory
> http://www.youtube.com/congruentlight
>
>


  • Prev by Date: Re: need something like ReplaceAllIndexed[]
  • Next by Date: Re: Sorting nested lists
  • Previous by thread: need something like ReplaceAllIndexed[]
  • Next by thread: Re: need something like ReplaceAllIndexed[]