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?



1 Answer 1


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]] *)
  • $\begingroup$ 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 :) $\endgroup$
    – Se314en
    May 23, 2016 at 13:03
  • $\begingroup$ Glad I could help! $\endgroup$
    – Jason B.
    May 23, 2016 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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