6
$\begingroup$

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

$\endgroup$
0

1 Answer 1

6
$\begingroup$

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.

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.