MathGroup Archive 2009

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

Search the Archive

Re: second simple problem

  • To: mathgroup at smc.vnet.net
  • Subject: [mg99760] Re: second simple problem
  • From: Szabolcs Horvát <szhorvat at gmail.com>
  • Date: Wed, 13 May 2009 05:09:12 -0400 (EDT)
  • References: <gu666q$9tf$1@smc.vnet.net> <gu8ugd$6se$1@smc.vnet.net>

Peter Pein wrote:
> Francisco Gutierrez schrieb:
>> 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      
>>
> Hi Francisco,
> sorry for not answering.
> Can anyone please explain, why the "obvious"
> Fold[Replace[#1, "M" -> #2] &, ex, {a, b}]
> leads to an unchanged "ex"? It is nearly 3 am and I guess it is better to go 
> to sleep, than to try to solve this one.

Hi Peter,

You fell into the mistake of thinking that Replace will replace only the 
first match in a list.  The difference between Replace and ReplaceAll is 
that Replace works on the whole expression by default, and not on any 
subparts.  We can tell it to work at a specific depth, e.g. 
Replace[list, a->b, {1}] replaces elements of the list, but this will 
replace *all* elements of list that match.

I cannot remember if there is a function/syntax that replaces only the 
first element found, and I cannot find one in the docs right now.  If 
you discover a simple way to do that, please let me know!

Perhaps we can use Replace[#1, {be___, "M", en___} :> {be, #2, en}] &, 
but that is rather ugly.


  • Prev by Date: Re: Introducing the Wolfram Mathematica Tutorial
  • Next by Date: Re: numbered figures
  • Previous by thread: Re: second simple problem
  • Next by thread: Re: Re: second simple problem