5

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

Natas
  • 2,310
  • 4
  • 14

1 Answers1

6

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.

WReach
  • 68,832
  • 4
  • 164
  • 269