What particular situation do we have to use RuleDelayed after replacement? [closed]

On the answer of How to impose normalization condition (not initial condition) on DSolve or NDSolve?

k = vars /. sol /. cs[[1]] /. C[_] :> 0 // N;

I see that in the documentation of ReplaceAll and examples of ReplaceAll on the internet, we use Rule (->) instead of RuleDelayed(:>) after ReplaceAll (/.). I don’t understand why RuleDelayed has to be used in the above answer.

Using rule:

k = vars /. sol /. cs[[1]] /. C[_] -> 0 // N;

can get the plots I want. But there must be something requiring the use of RuleDelayed in the above answer. What is this?
Thank you very much.



1 Answer


Here is what might be considered a classic example of the difference. Suppose I have a list containing a number of xs and maybe some other elements, and I want to replace the xs with random integers in some range, but I want new random draw for each replacement.

SeedRandom[42]; {x, y, x, x, y} /. x -> RandomInteger[9]

{6, y, 6, 6, y}

doesn’t work because RandomInteger only get called once, before any replacements are made. However,

SeedRandom[42]; {x, y, x, x, y} /. x :> RandomInteger[9]

{6, y, 0, 8, y}

works just fine because the rule evaluation is delayed and only made when the rule is used. See RuleDelayed