Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #15959 > unrolled thread

Re: Apply a rule to an expression only once

Started byBob Hanlon <hanlonr@cox.net>
First post2011-02-11 09:19 +0000
Last post2011-02-11 09:19 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.soft-sys.math.mathematica


Contents

  Re: Apply a rule to an expression only once Bob Hanlon <hanlonr@cox.net> - 2011-02-11 09:19 +0000

#15959 — Re: Apply a rule to an expression only once

FromBob Hanlon <hanlonr@cox.net>
Date2011-02-11 09:19 +0000
SubjectRe: Apply a rule to an expression only once
Message-ID<ij2uu5$7ss$1@smc.vnet.net>
expr = f a + f b;

rule = f p_ :> f[p];

MapAt[Replace[#, rule] &, expr, 1]

b f + f[a]

MapAt[ReplaceAll[#, rule] &, expr, 1]

b f + f[a]


Bob Hanlon

---- Guido Walter Pettinari <coccoinomane@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.



--

Bob Hanlon

[toc] | [standalone]


Back to top | Article view | comp.soft-sys.math.mathematica


csiph-web