# Generate pattern held by HoldPattern

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".

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.

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