Skip to main content

pattern matching - MatchQ’ing Except[…] and Except[…]


A PostScriptForm1 for Mathematica must recurse over the likes of Plus[…]. Output should be as follows:



  • 9+n: either 9 n add or n 9 add

  • 9-n: 9 n sub

  • -9+n: n 9 sub


  • -9-n: -9 n sub


So for my purposes first step is to find the first item of a list that is neither Times[-1, _] nor (n_Integer /; n < 0). But Position[(9 + n), (Except[Times[-1, _]] && Except[(n_Integer /; n < 0)]), 1, Heads -> False] returns a grumble: “Except::named: "Named pattern variables are not allowed in the first argument of Except[n_Integer/;n<0]”.


Please, kind experts of Mathematica.StackExchange.com, how could this most naturally be done?


This problem has raised other issues — likely to be my failure to master Mathematica’s object model.


thing = 9 (* Easy peasy *)
MatchQ[thing, (Except[Times[-1, _]])] (* returns True: happiness *)
MatchQ[thing, (Except[_?Negative])] (* also returns True: happiness *)
MatchQ[thing, (Except[Times[-1, _]] && Except[_?Negative])] (* returns False in Mathematica 9.0 (January 24, 2013): why? *)


Guidance would be most welcome. Thank you.



Answer



You can combine two or more exceptions with Alternatives (|)


MatchQ[thing, Except[Times[-1, _] | _?Negative]]


True



Comments