Given a symbolic expression how to find if starts with a minus or not?
You can do it the way a human does it: Look for the "-"
in the string.
#==1&/@StringCount[ToString/@InputForm/@negativeTruetests,Alternatives["-",Repeated["("]~~"-"]]
{True,True,True}
#==1&/@StringCount[ToString/@InputForm/@negativeFalseTests,Alternatives["-",Repeated["("]~~"-"]]
{False,False,False}
There are probably many creative ways to break this one horribly, but for the test cases it works:
(# /. Thread[Variables[#] -> 1]) < 0 & /@ negativeTruetests
(* {True, True, True, True, True, True} *)
(# /. Thread[Variables[#] -> 1]) < 0 & /@ negativeFalseTests
(* {False, False, False, False, False} *)
I will use your test lists alone as reference. If they are incomplete you will need to update the question.
When looking for a pattern for a group of expressions it is helpful to look at their TreeForm
:
TreeForm /@ {negativeTruetests (*sic*), negativeFalseTests} // Column
You see that your True expressions always have the head Times
with one negative leaf, be it -1
, -2
or a Rational
that is negative. Your False expressions either have head Times
or Power
but in the case of Times
they do not have a negative leaf. Therefore for these expressions you may use:
p = _. _?Negative;
MatchQ[#, p] & /@ negativeTruetests
MatchQ[#, p] & /@ negativeFalseTests
{True, True, True, True, True, True}
{False, False, False, False, False}
Because of the Optional
and OneIdentity
(1) this pattern will also handle a negative singlet:
MatchQ[#, p] & /@ {-Pi, 7/22}
{True, False}
Format-level pattern matching
Since it was revealed that this question relates to formatting it may be more appropriate to perform the test in that domain.
I will use a recursive pattern as I did for How to match expressions with a repeating pattern after converting to boxes with ToBoxes
:
test = MatchQ[#, RowBox[{"-" | _?#0, __}]] & @ ToBoxes @ # &;
test /@ negativeTruetests
test /@ negativeFalseTests
{True, True, True, True, True, True}
{False, False, False, False, False}
Another approach is to convert to a StandardForm
string and use StringMatchQ
, which is essentially the same as the test above because StandardForm
uses encoded Boxes:
test2 = StringMatchQ[ToString[#, StandardForm], ("\!" | "\(") ... ~~ "-" ~~ __] &;
test2 /@ negativeTruetests
test2 /@ negativeFalseTests
{True, True, True, True, True, True}
{False, False, False, False, False}