17
$\begingroup$

The documentation on RuleDelayed states that lhs :> rhs represents a rule that transforms lhs to rhs, evaluating rhs only after the rule is used.

Consider the following rule:

a/;condition :> (condition=False; RandomReal[])

When this rule is used, it sets the variable condition to False, and therefore the lefthand side of the rule cannot be matched any more. So I expected that in the following command only the first symbol a would be replaced by a real number.

condition=True;
{a,a,a} /. a/;condition :> (condition=False; RandomReal[])
(* {0.420057,0.183578,0.751358} *)

But all three are replaced, so the rule is used three times. What is going on here?

$\endgroup$

1 Answer 1

18
$\begingroup$

There seems to be a subtlety in the way delayed rules are used. Have a look at the following:

{a,a,a} /. a/;(Print["lhs evaluated"];True) :>(Print["rhs valuated"]; RandomReal[])

(*lhs evaluated
  lhs evaluated
  lhs evaluated
  rhs evaluated
  rhs evaluated
  rhs evaluated *)

(* {0.797753,0.567294,0.91182} *)

This shows that when we use a delayed rule on an expression, first all matching subexpressions are replaced with the still unevaluated righthand side of the rule, and only then the resulting expression is evaluated. That is also shown in the following variant, where the expression cannot be further evaluated:

Hold[a,a,a] /. a/;(Print["lhs evaluated"];True) :>(Print["rhs evaluated"];RandomReal[])

(* lhs evaluated
   lhs evaluated
   lhs evaluated *)

(* Hold[Print[rhs evaluated];RandomReal[],Print[rhs evaluated];RandomReal[],Print[rhs evaluated];RandomReal[]] *)

In both examples the result is as it has to be. When you want to make a rule that has to be used only once, the implementation for doing so must be given in the lefthand side of the rule or in a condition on the rule itself:

condition=True;
{a,a,a} /. a :> RandomReal[] /; If[condition, condition=False;True, False]

(* {0.338583,a,a} *)
$\endgroup$
2
  • 4
    $\begingroup$ +1. I reached the same conclusions a few years ago. I am actually quite surprised that this question has not been asked yet here on SE, but if memory serves, it hasn't indeed. $\endgroup$ Commented Oct 28, 2015 at 15:38
  • $\begingroup$ This is a very nice implementation of "Replace First", +1 $\endgroup$
    – LLlAMnYP
    Commented Oct 28, 2015 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.