Sorry. I made multiple typos in the first paragraph of my original question. I should have said:
MemberQ
takes a list as its first argument. (Actually, this is not true. As Michael Rogers points out elsewhere on this page, MemberQ
can take any head as its first argument, not just List
.)
MatchQ
takes an expression as its first argument.
I'm trying to understand how to write a pattern representing the notion "any subexpression containing the symbol a
anywhere."
If I have a string, I can write a string pattern (StringExpression
) representing the notion "a string containing the character a
" simply by writing ___ ~~ "a" ~~ ___
. This string pattern can be used as the second argument to StringMatchQ
:
StringMatchQ["abc", ___ ~~ "a" ~~ ___]
StringMatchQ["baac", ___ ~~ "a" ~~ ___]
StringMatchQ["xyz", ___ ~~ "a" ~~ ___]
(* OUTPUT: *)
(* True *)
(* True *)
(* False *)
But what is the analogue for the symbol a
in a (general) pattern, rather than the character "a"
in a string pattern? The following is obviously invalid syntax:
MatchQ[Times[Power[x, a], Power[y, b], Power[z, c]], ___ ~~ a ~~ ___]
(* OUTPUT: *)
(* False *)
Is there a way to write a pattern representing "any expression with a subexpression a
anywhere" for use as the second argument to MatchQ
? That's my question. Thanks to Michael Rogers's suggestion elsewhere on this page, it turns out that this does the trick:
MatchQ[Times[Power[x, a], Power[y, b], Power[z, c]], _[___, a, ___]_]
(* OUTPUT: *)
(* True *)
But I don't think I understand why. Is _[___, a, ___]_
a regex-like syntax?
Alternatively, I can obtain the result I want more simply using the resource function ContainsQ
:
ResourceFunction["ContainsQ"][Times[Power[x, a], Power[y, b], Power[z, c]], a]
(* OUTPUT: *)
(* True *)
I can also obtain the result I want using MemberQ
, though not directly (as far as I can tell) because a
is in the exponent:
MemberQ[Times[Power[x, a], Power[y, b], Power[z, c]], a]
MemberQ[Times[Power[x, a], Power[y, b], Power[z, c]], Power[x, a]]
(* OUTPUT: *)
(* False *)
(* True *)
My observation is, ContainsQ
is quite useful! So my follow-up question is, why didn't (or doesn't) Wolfram include ContainsQ
as a built-in function? The answer is probably "because you can just use MatchQ
in the way Michael Rogers suggested elsewhere on this page":
MatchQ[Times[Power[x, a], Power[y, b], Power[z, c]], _[___, a, ___]_]
(* OUTPUT: *)
(* True *)