1
$\begingroup$

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?

$\endgroup$
3
  • 2
    $\begingroup$ Change Rule ( ->) to RuleDelayed ( :>). $\endgroup$
    – kglr
    Dec 1, 2014 at 2:06
  • 1
    $\begingroup$ @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. $\endgroup$ Dec 1, 2014 at 4:11
  • $\begingroup$ just posted the comment as an answer. Re "... why ... in the Comments ..", i wasn't sure if it would be a complete answer. $\endgroup$
    – kglr
    Dec 1, 2014 at 10:45

1 Answer 1

0
$\begingroup$

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 *)
$\endgroup$

Your Answer

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

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