Re: Apply a rule to an expression only once

• To: mathgroup at smc.vnet.net
• Subject: [mg116364] Re: Apply a rule to an expression only once
• From: DrMajorBob <btreat1 at austin.rr.com>
• Date: Sat, 12 Feb 2011 05:17:51 -0500 (EST)
• References: <201102110915.EAA07895@smc.vnet.net>

```Much better!

On Fri, 11 Feb 2011 03:15:54 -0600, Andrzej Kozlowski <akoz at mimuw.edu.pl>
wrote:

> One simple way that appears to achieve what you want (or seem so) is to
> use Replace instead of ReplaceAll. After all, you do not want to
> "replace all", do you?
>
> So
>
> expr = f a + f b;
>
> rule = f p_ + x_ :> f[p] + x
>
> Replace[expr, rule]
>
> f[a] + b*f
>
> ?
>
> Andrzej Kozlowski
>
> On 10 Feb 2011, at 19:22, Guido Walter Pettinari 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 [ { },
>>  ],
>>
>> 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.
>>
>>
>

--
DrMajorBob at yahoo.com

```

• Prev by Date: Re: k-permutations enumeration
• Next by Date: Re: k-permutations enumeration
• Previous by thread: Re: Apply a rule to an expression only once
• Next by thread: Re: Apply a rule to an expression only once