MathGroup Archive 2009

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

Search the Archive

Re: second simple problem

  • To: mathgroup at smc.vnet.net
  • Subject: [mg99700] Re: second simple problem
  • From: Szabolcs Horvát <szhorvat at gmail.com>
  • Date: Mon, 11 May 2009 06:26:52 -0400 (EDT)
  • References: <gu666q$9tf$1@smc.vnet.net>

Francisco Gutierrez wrote:
> Dear sirs:
> I have the following list:
> ex={1,5,7,4,"M",6,7,8,9,1,"M",3}
> I want to replace the M's in the following way: the first M by 5, and the second by2.
> Thus I have a replacement list
> rL={5,2}
> The problem is to get ={1,5,7,4,5,6,7,8,9,1,2,3}
> How can I do this in the most general form (for any length of ex and any number of values of "M")?
> Thanks
> Francisco      
> 

ms = {5, 2}

This was my first thought, but it makes me feel ill at ease ... a 
replacement should not have any side effects, and we should not count on 
the RHS of the rule being evaluated precisely once for each item replaced.

Module[{c = 1}, ex /. "M" :> (ms[[c++]])]

So here's a possibly better solution:

ReplacePart[ex, Thread[Position[ex, "M"] -> ms]]


  • Prev by Date: Re: simple question
  • Next by Date: Re: simple Question
  • Previous by thread: Re: second simple problem
  • Next by thread: Re: second simple problem