Re: Re: second simple problem

• To: mathgroup at smc.vnet.net
• Subject: [mg99789] Re: [mg99760] Re: second simple problem
• From: Leonid Shifrin <lshifr at gmail.com>
• Date: Thu, 14 May 2009 01:43:21 -0400 (EDT)
• References: <gu666q\$9tf\$1@smc.vnet.net> <gu8ugd\$6se\$1@smc.vnet.net>

```Hi Szabolcs,

>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!

One way is to define our own  single-replacement function, like this:

In[1] =

Clear[replaceOnce];
replaceOnce[expr_, rule : (_RuleDelayed | _Rule)] :=
With[{onceonly =
Module[{used = False},
rule /. (head : (RuleDelayed | Rule))[lhs_, rhs_] :>
head[lhs /; ! used && (used = True), rhs]]},
expr /. onceonly];

In[2] = replaceOnce[Range[4, 10], x_?OddQ :> x^2]

Out[2] = {4, 25, 6, 7, 8, 9, 10}

In[3] = replaceOnce[Range[4, 10], x_?OddQ -> 100]

Out[3] = {4, 100, 6, 7, 8, 9, 10}

This does induce some overhead though. Also,  I did not test it extensively
enough to be sure that it will always work.

Regards,
Leonid

2009/5/13 Szabolcs Horv=E1t <szhorvat at gmail.com>

> 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 a=
ny
> 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: Assign new values to matrix using indices
• Next by Date: Re: Re: second simple problem - Follow-up
• Previous by thread: Re: second simple problem
• Next by thread: Palette Management