1
$\begingroup$

I was playing with pattern matching and I ran into something I didn't expect. I imagine the following line would return True, but it returns False:

MatchQ[x, (+1 | -1) a_]

This will return True:

MatchQ[-x, (+1 | -1) a_]

Digging slightly deeper with FullForm I find the reason for this; FullForm[-a] returns Times[-1, a] whereas FullForm[a], of course, returns a. What's the best way to return True for both cases? Does Mathematica have an equivalent to the ? symbol in regular expressions which matches a group zero or one times?

I've also tried

MatchQ[x, (Nothing | -1) a_]

which again returns False.

$\endgroup$
3
  • 2
    $\begingroup$ This would work: MatchQ[x, fact_. a_Symbol /; Abs[fact] == 1] It matches only if the factor in front of a symbol is +1 or -1. Nothing is not meant to be used in pattern matching. $\endgroup$
    – Szabolcs
    Sep 6, 2016 at 18:57
  • $\begingroup$ What would be an example of a match failure you would hope to see with the pattern you are searching for? $\endgroup$
    – Alan
    Sep 6, 2016 at 20:12
  • $\begingroup$ @Szabolcs Thank you, _. was just what I needed to know about. @Alan 2x would fail to match. $\endgroup$
    – alessandro
    Sep 6, 2016 at 23:32

1 Answer 1

2
$\begingroup$

FullForm (and Head) is useful in seeing what lies under the hood.

FullForm@x

x

Head@x

Symbol

and

FullForm@-x

Times[-1,x]

Head@-x

Times

Now

(+1 | -1) a_ // FullForm

Times[Alternatives[1,-1],Pattern[a,Blank[]]]

That's why -x matches the pattern and x does not. For a fix:

MatchQ[x, -1 a_ | _Symbol]

True

MatchQ[-x, -1 a_ | _Symbol]

True

MatchQ[2 x, -1 a_ | _Symbol]

False

MatchQ[-2 x, -1 a_ | _Symbol]

False

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.