4
$\begingroup$

I am trying to match against products of elements with a specific pattern. Since a product of symbols A B C is just Times[A,B,C], I figured this could be done by treating Times like any other symbol (here f):

MatchQ[ f[a,b,c], f[_Symbol..] ]
>>> True

Woe, such a pattern doesn't seem to work for Times:

MatchQ[ a b c, Times[_Symbol..] ]
>>> False

MatchQ[ Times[a, b, c], Times[_Symbol..] ]
>>> False

I suspect this may be due to some property of Times related to its commutativity, though there's no auto-commuting in this example!

a b c // FullForm
>>> Times[a, b, c]

How can I produce the desired pattern for matching repeated-pattern arguments of Times?

$\endgroup$
1

1 Answer 1

6
$\begingroup$

You need wrap the pattern Times[...] with HoldPattern or Verbatim to prevent Times[_Symbol ..] evaluating to _Symbol.. before MatchQ does its work:

MatchQ[a b c, HoldPattern[Times][_Symbol ..]]

True

MatchQ[a b  c, Verbatim[Times][_Symbol ..]]

True

MatchQ[Times[a, b, c], HoldPattern[Times][_Symbol ..]]

True

MatchQ[Times[a, b, c], Verbatim[Times][_Symbol ..]]

True

$\endgroup$

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