1

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}]]
Bruno Le Floch
  • 1,959
  • 10
  • 23
  • 1
    @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]." – Bruno Le Floch May 30 '16 at 19:38
  • Indeed, this is true. – Leonid Shifrin May 30 '16 at 19:44
  • 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?). – Bruno Le Floch May 30 '16 at 19:44
  • 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. – Rolf Mertig May 30 '16 at 19:51
  • @RolfMertig Interesting. Indeed so, I tested now. Didn't test for my prev. comment, since this didn't work before, and I knew that. The moral is to always test :) – Leonid Shifrin May 30 '16 at 19:56
  • 1
    @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). – Leonid Shifrin May 30 '16 at 20:00
  • @LeonidShifrin: I should probably delete my question: it is also a duplicate of http://mathematica.stackexchange.com/q/88375/39260 which has an answer with double-Except by Simon Rochester. Right now I'm trying to cook up some code that will allow rule-replacement, i.e. such that x/.AndRuleDelayed[{patt1,patt2},replacement] is equivalent to {x,x}/.{patt1,patt2}:>replacement when both patterns match, and the replacement is allowed to involve named subpatterns from both patt1 and patt2. Not sure where I should post that code. – Bruno Le Floch May 30 '16 at 20:06
  • @BrunoLeFloch You could add it as an answer to either of those past discussions. – Leonid Shifrin May 30 '16 at 20:50
  • @LeonidShifrin: FYI, I've posted a separate question (http://mathematica.stackexchange.com/questions/116302/opposite-of-alternatives-in-a-rule) with a focus on rules rather than patterns because both earlier questioners seem to only care about patterns. – Bruno Le Floch May 30 '16 at 21:05

0 Answers0