Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2007
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2007

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

Search the Archive

Re: Replacing list elements while retaining structure

  • To: mathgroup at smc.vnet.net
  • Subject: [mg73996] Re: Replacing list elements while retaining structure
  • From: Jens-Peer Kuska <kuska at informatik.uni-leipzig.de>
  • Date: Mon, 5 Mar 2007 04:49:35 -0500 (EST)
  • References: <esdj70$olc$1@smc.vnet.net>

Hi,

with

structurize[expr_, repl_] :=
   Block[{replaceList = repl, doReplace},
     doReplace[a_List] := doReplace /@ a;
     doReplace[a_] /; replaceList =!= {} :=
       Module[{f}, f = First[replaceList];
        replaceList = Rest[replaceList];
        f];
     doReplace[{a_List, b__}] :=
       {doReplace[a], Sequence @@ doReplace[{b}]};
     doReplace[a_] := a;
     doReplace[expr]
     ]

structurize[{x, x, {{x}, x}, x}, {1, 2, 3, 4, 5}]

gives

{1, 2, {{3}, 4}, 5}

Regards
   Jens


D. Grady wrote:
> Okay, so I have two lists, X and Y.  X has some complex structure
> which is important, but the values contained in X are not important.
> Y has values that are important, but the structure of Y is not.  I was
> to sequentially replace all the elements in X with the elements of Y.
> 
> It's assumed that X and Y have the same total number of elements, i.e.
> Length[Flatten[X]] == Length[Flatten[Y]]
> 
> Here is an example:
> 
> In[8]:=
> structurize[{x,x,{{x},x},x},{1,2,3,4,5}]
> 
> Out[8]=
> {1,2,{{3},4},5}
> 
> This is what I have so far:
> 
> structurize[X_List, Y_List] := ReplacePart[X, Flatten[Y], Position[X,
> a_ /; \
> (Head[a] =!= List), Heads -> False],
>       Table[{i}, {i, 1, Length[
>         Flatten[Y]]}]] /; Length[Flatten[X]] == Length[Flatten[Y]]
> 
> This works fine so long as the elements of X are atomic expressions;
> however, if there is an element of X which is a more complicated
> expression, like x^2, then this function does not work as desired
> because the pattern in Position[] matches x^2 as well as x and 2.  Is
> there a way to avoid matching parts of a subexpression?  Is there a
> better way to approach the problem from the get-go?
> 
> Thanks in advance!
> 
> 


  • Prev by Date: RE: Rigid body equations
  • Next by Date: Re: Integrals involving square roots
  • Previous by thread: Re: Replacing list elements while retaining structure
  • Next by thread: Re: Replacing list elements while retaining structure