TransWikia.com

Pattern matching functions of variables

Mathematica Asked on January 25, 2021

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?

One Answer

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 *)

Correct answer by kglr on January 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP