Group Abstract Group Abstract

Message Boards Message Boards

0
|
37 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

How to reproduce the behavior of MemberQ[{a, b}, a] using MatchQ instead

Posted 22 hours ago

I have been thinking how MemberQ is a sort of special case of MatchQ. MemberQ assumes a list, rather than simply a pattern, as MatchQ does -- as its second argument. For example:

MemberQ[{a, b}, a]
MatchQ[{a, b}, {___, a, ___}]
MatchQ[{a, b}, {___, ___, a, ___, ___}]
MatchQ[{a, b}, List[___, a, ___]]
MatchQ[{a, b}, List[___, ___, a, ___, ___]]

(* OUTPUT: *)
(* True *)
(* True *)
(* True *)
(* True *)
(* True *)

Is there any way to write the pattern in MatchQ without explicitly specifying the List? I'm thinking of something like the following: MatchQ[{a, b}, ___ ~~ a ~~ ___]

...but that's incorrect syntax (and returns False) because the use of ~~ implies a StringExpression, and {a, b} is clearly not a StringExpression. So, how can I write a pattern representing "any subexpression containing the symbol a anywhere"?

I could accomplish this using the resource function ContainsQ:

ResourceFunction["ContainsQ"][{a, b}, a]

(* OUTPUT: *)
(* True *)

But what is the built-in way to do this?

Looking at the source notebook for the resource function ContainsQ, I see that the definition of ContainsQ is simply:

ContainsQ[args___] := (Needs["GeneralUtilities`"]; GeneralUtilities`ContainsQ[args])
POSTED BY: Andrew D
2 Replies
Posted 21 hours ago

I'm sorry, but I'm very confused. You said,

MemberQ assumes a list, rather than simply a pattern ... as its second argument.

But then you give the example of MemberQ[{a, b}, a]. So, clearly you didn't write what you meant.

Then you ask for a pattern that works with MatchQ, but later you say that ContainsQ does what you want (but isn't built-in).

So, do you really need MatchQ? Why can't you use MemberQ just like ContainsQ? Maybe you should tell us more about the problem you're trying to solve rather than pre-constraining the discussion to specific symbols that you've already tried.

POSTED BY: Eric Rimbey

Note MemberQ[a + b + c, a] returns True, so any head is allowed.

I think you want MatchQ[list, {___, a, ___}]. Or more generally, MatchQ[expr, _[___, a, ___]].

POSTED BY: Michael Rogers
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard