How can one match a function in a replacement rule

I'm trying to write a delayed replacement rule that is capable of matching both the functions and their parameters, like

h[1, k[2, x]] /. {f[n_, g[m_, x] _] _ :> f[0, g[m + n, x]]}


The idea would be that I get the output h[0,k[3,x]] for the example I give here. However, obviously the point is that I want the rule to also match, for example f[3,g[5,x]] and give the answer f[0,g[8,x]]. Is it possible to write such a rule?

Thanks.

1 Answer

Put the underscore after the name of the Head instead of after the final square brackets,

h[1, k[2, x]] /. {f_[n_, g_[m_, x] ] :> f[0, g[m + n, x]]}
(* h[0, k[3, x]] *)

f[3, g[5, x]] /. {f_[n_, g_[m_, x] ] :> f[0, g[m + n, x]]}
(* f[0, g[8, x]] *)

• Great, thanks. I was getting myself confused because I was also trying to apply a match to the functions like f_?opQ[m_,g_?opQ[n_,x]], for a defined function opQ, so I tried the underscore straight after f and g, and at the end, but didn't try at the front without the extra rule. Then it seems the rule is added after, so f_[m_,g_[n_,x]?opQ]?opQ finally does what I need. Thanks for the help :) – Se314en May 23 '16 at 13:03
• Glad I could help! – Jason B. May 23 '16 at 13:08