# prograMing: ReplacePart problem

```"Scott Morrison" <scott@morrison.fl.net.au> wrote:

> I have a list of pairs of the form:
> gt»3,5},{{},6},{7,{}},{{},{}},{{},56},{{},3}};
>
> The empty lists inside pairs are being used as placeholders. I want to
> replace these with the elements of b: bº1,a2,a3,a4,a5,a6};
> hopefully resulting in the list
> {{3,5},{a1,6},{7,a2},{a3,a4},{a5,56},{a6,3}}
>
> I had thought that ReplacePart could do this

This is an interesting problem. Many people already gave solutions.
Here
I'll generalize this problem a bit.

Problem: Suppose you have an expression that contains n "slots" that
you
want to fill-in using another list of length n. How to do it?

The problem is not completly specified above because the correspondence
between slots in expr and replacementList is not clear. Since
Mathematica
expressions are just trees, each slot has an index. The length of
slot's
index may or may not be used to determine the replacement order. For
example, should a slot with index {1,1,1} come before or after another
slot
with index {1,2}? Anyhow, ReplaceParts should be the right function to
solve this problem. The current four-argument-form behavior of
ReplaceParts
is probably a bug. Here's a substitute.

Clear[ReplaceMultiplePart];
ReplaceMultiplePart::"usage"  "ReplaceMultiplePart[expr,newPartList,positionIndexList] replaces
parts of
expr corresponding positionIndexList with newPartList. Usage Example:
ReplaceMultiplePartPart[f[1,2,3],{hal,x},{{0},{2}}]";

ReplaceMultiplePart[expr_,newParts_List,posIndexes_List]:
Fold[ReplacePart[#1,Sequence@@#2]&,expr,Transpose[{newParts,posIndexes}]];

Now we can use ReplaceMultiplePart to solve the generalized problem.

In[23]:Clear[aTree,replacementList];
aTreeûg[slot,{slot,p}][slot,slot],slot,m,slot[slot]];
replacementListºnge@7;

Out[24]{{1,0,1},{1,0,2,1},{1,1},{1,2},{2},{4,0},{4,1}}

In[25]:(*assuming the order returned by Position is the desired one*)
ReplaceMultiplePart[aTree,replacementList,pos]

Out[25]f[g[1,{2,p}][3,4],5,m,6[7]]

Xah, xah@best.com
http://www.best.com/~xah/Wallpaper_dir/c0_WallPaper.html
Mathematics, when viewed from the right angle, can be as boring as one
could imagine.    --Mathematcian's lore

```

• Prev by Date: Re: I don't understand in Mathematic
• Next by Date: Symbolic Orthogonalisation of Function spaces
• Prev by thread: Re: A bug in DesignedRegress?
• Next by thread: Symbolic Orthogonalisation of Function spaces