ReplaceRepeated

expr//.rules

repeatedly performs replacements until expr no longer changes.

ReplaceRepeated[rules]

represents an operator form of ReplaceRepeated that can be applied to an expression.

Details and Options

  • expr//.rules effectively applies /. repeatedly, until the results it gets no longer change.
  • It performs one complete pass over the expression using /., then carries out the next pass.
  • You should be very careful to avoid infinite loops when you use the //. operator. The command x//.x->x+1 will, for example, lead to an infinite loop.
  • ReplaceRepeated takes the option MaxIterations, which specifies the maximum number of times it will try to apply the rules you give. The default setting is MaxIterations->65536. With MaxIterations->Infinity there is no limit.
  • ReplaceRepeated[rules][expr] is equivalent to ReplaceRepeated[expr,rules].

Examples

open allclose all

Basic Examples  (3)

Apply rules for the power and product laws for logarithms of real numbers recursively:

ReplaceAll does just a single replacement:

Remove all occurrences of a head, including nested ones:

ReplaceAll would only remove the outermost head:

Use ReplaceRepeated in operator form:

Scope  (3)

If no rule matches, the input expression is returned:

Replace occurrences of f with 1 followed by exactly one integer:

Replace occurrences of f with 1 followed by one or more integers:

Replace occurrences of f with 1 followed by zero or more integers:

ReplaceRepeated works inside held expressions:

Do not evaluate the right-hand side of the rule before doing the replacement:

Evaluate the right-hand side before replacement:

Applications  (1)

Undo "currying" of function arguments:

Properties & Relations  (5)

An empty list is considered to have no matching rules:

When a list of lists is used for replacement, the result is a list of the same length:

Evaluation is not forced when replacing into a held expression:

ReplaceRepeated is effectively a combination of ReplaceAll and FixedPoint:

ReplaceRepeated scans multiple times from the top of an expression:

ReplaceAll replaces the largest subexpressions it can and then stops:

Replace with level spec All will attempt to replace every subexpression exactly once:

Introduced in 1988
 (1.0)
 |
Updated in 2018
 (11.3)