Given a list of patterns {x, y, z} I want a pattern that matches if and only if each pattern matches. If instead of getting the intersection of patterns I wanted the union of patterns I could use Alternatives.

I managed to write the following. Is there a better alternative?

Except[Alternatives @@ Map[Except, {x, y, z}]]
  • 1
    $\begingroup$ @LeonidShifrin: Thanks for locating that other question, I had not seen it. I did more tests, and the solution with Except does not work because named patterns are not allowed. E.g. I tried MatchQ[Pi+1,Except[Except[a_?NumericQ],b_Plus]] and got Except::named: "Named pattern variables are not allowed in the first argument of Except[a_?NumericQ]." $\endgroup$ May 30, 2016 at 19:38
  • $\begingroup$ Indeed, this is true. $\endgroup$ May 30, 2016 at 19:44
  • $\begingroup$ In my specific use-case (defining a function f which defaults to Hold and takes special values when several patterns (with named variables) match simultaneously), I can define f[a_]:=g[a,a] and g[a:pattern1, a:pattern2]:=value which will only match if the argument matches both pattern1 and pattern2, but it looks somewhat ugly (and slow?). $\endgroup$ May 30, 2016 at 19:44
  • $\begingroup$ In Mathematica 10.4.1 under Windows (and Linux) I get no error message for MatchQ[Pi + 1, Except[Except[a_?NumericQ], b_Plus]], but True. $\endgroup$ May 30, 2016 at 19:51
  • 1
    $\begingroup$ @BrunoLeFloch To make your request more formal, the task is to construct the logical And for patterns using only the pattern-matcher, and not using the evaluator (Condition, PatternTest, etc.). If we formulate it this way, then I don't see any other option except double - Except (pun intended). $\endgroup$ May 30, 2016 at 20:00


Browse other questions tagged or ask your own question.