# Pattern matching functions of variables

I am trying work with a general operator z[] and later plug in candidate forms for z[]. But pattern matching turns the inside z[] into a constant and can no longer perform operations on it:

r = z[(x + 2)^2];
r /. z[a_] -> Expand[a]
r /. z[a_] -> Integrate[a, {x, 0, 10}]


Results in:

(*   (2 + x)^2   *)
(*    10 (2 + x)^2    *)


I would like it to return:

4 + 4x + x^2

1720/3

What's going wrong here?

• Change Rule ( ->) to RuleDelayed ( :>).
– kglr
Dec 1, 2014 at 2:06
• @kguler Thanks, that fixed it. Can you tell me now why so many people post good answers in the Comments instead of the Answer slot? I can Accept it if put it in the Answer slot. Dec 1, 2014 at 4:11
• just posted the comment as an answer. Re "... why ... in the Comments ..", i wasn't sure if it would be a complete answer.
– kglr
Dec 1, 2014 at 10:45

Changing Rule to RuleDelayed

r = z[(x + 2)^2];
r /. z[a_] :> Expand[a]
(* 4 + 4 x + x^2 *)
r /. z[a_] :> Integrate[a, {x, 0, 10}]
(* 1720/30 *)


gives the desired output.

Alternatively, you can use Rule to replace the Head z with the desired function:

r = z[(x + 2)^2];
r /. z -> Expand
(* 4 + 4 x + x^2 *)
r /. z -> (Integrate[#, {x, 0, 10}] &)
(* 1720/30 *)