I am trying to match expressions that have factors with certain exponents. For instance, I would like to match as follows

expr = a^2 * b^2;
MatchQ[expr, HoldPattern[Times[_^2, _^2]]]

This is fine. The problem I want to solve now is, given a list of exponents to generate a pattern that matches any expression which has factors with said exponents. What I tried for the above example is the following

exponents = {2, 2};
pattern = With[{list = _^#& /@ exponents}, HoldPattern[Times@@list];

But this does not work, since the pattern reads Times@@{_^2, _^2} instead of Times[_^2, _^2].

Is there a way to insert the arguments into a HoldPattern programatically?

One way I could imagine is that you do something like f@@(_^#& /@ exponents) and then replace f by Times, but I cannot see how to do this while keeping the arguments "unevalutated".


1 Answer 1


One way to is to use direct replacement:

exponents = {2, 2};

_^# & /@ exponents /. {e__} :> HoldPattern[Times[e]]

(* HoldPattern[_^2 * _^2] *)

For more elaborate mechanisms that partially evaluate held expressions, see Replacement inside held expression.

  • 2
    $\begingroup$ +1. I think, this particular method got a name "injector pattern" on this site. $\endgroup$ Mar 15, 2020 at 21:15
  • $\begingroup$ @LeonidShifrin Thank you for the terminology. $\endgroup$
    – Natas
    Mar 16, 2020 at 6:39

Your Answer

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

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