MathGroup Archive 2011

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

Search the Archive

Re: Apply a rule to an expression only once

  • To: mathgroup at smc.vnet.net
  • Subject: [mg116313] Re: Apply a rule to an expression only once
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Fri, 11 Feb 2011 04:12:07 -0500 (EST)

Hi Guido,

I don't think this is possible without modifying the rule. But the latter
can be done programmatically.
I suggested a way here:

http://groups.google.com/group/comp.soft-sys.math.mathematica/browse_thread/thread/2cfea08615b3aefe

which is similar to your workaround, but the rule is modified
programmatically, and the variable is a persistent
local variable created with Module, so you don't create global variables.

Regards,
Leonid

On Thu, Feb 10, 2011 at 1:22 PM, Guido Walter Pettinari <
coccoinomane at gmail.com> wrote:

> Hello group!
>
> Does anybody know how to apply a rule to an expression only once?
> In other words, is it possible to tell ReplaceAll to stop after the
> first application of a rule?
>
> Simple example:
>
> expr = f a + f b;
> rule = f p_ :> f [p];
> ReplaceAll [ expr, rule ]
>
> The output, as expected, is:
> f [a] + f [b]
>
> However, what I want is something like:
>
> ReplaceAll [ expr, rule, OnlyFirst -> True ]
>
> that gives the output
>
> f [a] + f b.
>
> My simple example can be solved by using ReplacePart, but alas it is
> not the kind of solution I am looking for.
>
> Thank you for your consideration!
>
> Best regards,
>
> Guido W. Pettinari
>
> P.S. I found a temporary solution by using a pattern test at the time
> of rule definition, i.e.
>
> rule = f p_ /; matchFirst[] :> f [p],
>
> with
>
> matchFirst [] := Module [ { },
>  If [ TrueQ@$alreadyMatched, False, $alreadyMatched = True; True]
>  ],
>
> but this does not satisfy me since (i) I do not want to alter the rule
> definition, and (ii)  I have to update the global variable
> $alreadyMatched every time I want to use the trick.
>
>
>


  • Prev by Date: Re: k-permutations enumeration
  • Next by Date: new Graph function + combinatorica: various problems
  • Previous by thread: Apply a rule to an expression only once
  • Next by thread: Re: Apply a rule to an expression only once