Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1998
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1998

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

Search the Archive

Re: ReplacePart question (2)

  • To: mathgroup at smc.vnet.net
  • Subject: [mg13205] Re: ReplacePart question (2)
  • From: "Allan Hayes" <hay at haystack.demon.cc.uk>
  • Date: Mon, 13 Jul 1998 07:42:53 -0400
  • References: <6nkvd3$17k@smc.vnet.net> <6nn9ng$583@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

I should have explained why I devised the previouly posted code for
MyReplacePart.
Tobias Oed has proposed using Fold, however this runs into difficulties
when one part to be replaced is a subpart of another:

expr={{a},b,c,d};
new={x,y,z};
pos={{1},{1,1},{4}} (* Positions of a and d in expr *);
npos={{2},{1},{3}}(* Positions of x and y in new - new could contain
other stuff *);

Fold[
 ReplacePart[#1,
  new,
  First[#2],
  Last[#2]
 ]&,
 expr,
 Thread[{pos,npos}]
]

ReplacePart::part: Part {1, 1} of {y, b, c, d} does not exist.
ReplacePart::psl:
   Position specification z in
    ReplacePart[{y, b, c, d}, {x, y, z}, {1, 1}, z]
     is not an integer or a list of integers.

ReplacePart[{y, b, c, d}, {x, y, z}, {1, 1}, z]

This can be avoided by removing some {1,1} from pos and {1} from npos,
and this could be put into the program. The depth first search use by
ReplaceAll in the code for MyReplaceAll make automatically takes care
of this problem.

MyReplacePart[expr_, rep_, expos:{___List}, repos:{___List}]:=
Module[{f},
 MapIndexed[f, expr,{0, Infinity}, Heads->True]/.
 Thread[f[_,#]&/@expos ->Extract[rep,repos]]/.f->(#&) ]

MyReplacePart[expr, new, pos,npos]

{y, b, c, x}

------------------------------------------------------------- Allan
Hayes
Training and Consulting
Leicester UK
http://www.haystack.demon.co.uk
hay at haystack.demon.co.uk
voice: +44 (0)116 271 4198
fax: +44(0)116 271 8642



  • Prev by Date: Re: Very strange Bug !?
  • Next by Date: Re: Derivatives D[ ] as Functions inside Tables; Need Help!
  • Previous by thread: Re: How to Extract a common factor from a Sum
  • Next by thread: Re: Piecewise defined functions