6
$\begingroup$

An expression like this one

a < x < b

is normally represented as

Less[a, x, b]

while an expression like

a < x <= b

is represented as

Inequality[a, Less, x, LessEqual, b]

(1) What is the reason of the following strange behavior of pattern matching and Inequality expressions?

MatchQ[Inequality[1, Less, x, LessEqual, 2], _Inequality]
MatchQ[Inequality[1, Less, x, LessEqual, 2], Inequality[___]]
MatchQ[Inequality[1, Less, x, LessEqual, 2], 
 Inequality[1, Less, x, LessEqual, 2]]
MatchQ[Inequality[1, Less, x, LessEqual, 2], 
 Inequality[_, Less, _, LessEqual, _]]
MatchQ[Inequality[1, Less, x, LessEqual, 2], 
 Inequality[1, _, x, LessEqual, 2]]
True
False
True
True
False

(2) How to do pattern matching properly with Inequality?

(3) Elegant way to convert all the Inequality in an expression to their normal form when possible (because of this problem)?

$\endgroup$
  • 3
    $\begingroup$ As for the first and second Inequality[___] evaluates to True immediately. Try HoldPattern[Inequality[___]] instead: that one then works. I think the issue is always pre-evaluation of the pattern. Look at what Inequality[1, _, x, LessEqual, 2] evaluates to. $\endgroup$ – march Mar 8 '16 at 18:41
  • 2
    $\begingroup$ Related: mathematica.stackexchange.com/questions/22948/… $\endgroup$ – Michael E2 Mar 8 '16 at 18:55
6
$\begingroup$

The issue is pre-evaluation of the pattern. For the ones that evaluate to False:

Inequality[___]
(* True *)

and

Inequality[1, _, x, LessEqual, 2]
(* Inequality[1, _, x] && x <= 2 *)

Neither of those evaluated forms will match

Inequality[1, Less, x, LessEqual, 2]

To fix this, merely add HoldPattern. For instance,

MatchQ[Inequality[1, Less, x, LessEqual, 2], HoldPattern[Inequality[___]]]
(* True *)
$\endgroup$
5
$\begingroup$

Inactivate is helpful in analyzing this problem.

Inactivate[
  Column[
    {MatchQ[Inequality[1, Less, x, LessEqual, 2], _Inequality],
     MatchQ[Inequality[1, Less, x, LessEqual, 2], Inequality[___]],
     MatchQ[
       Inequality[1, Less, x, LessEqual, 2], 
       Inequality[1, Less, x, LessEqual, 2]],
     MatchQ[
       Inequality[1, Less, x, LessEqual, 2], 
       Inequality[_, Less, _, LessEqual, _]],
     MatchQ[
       Inequality[1, Less, x, LessEqual, 2], 
       Inequality[1, _, x, LessEqual, 2]]}],
 MatchQ]

result

The above results show clearly why the second and last forms evaluate to False. They also suggests a work-around.

Inactivate[
  MatchQ[
    Inequality[1, Less, x, LessEqual, 2], 
    Inequality[1, Less, x, LessEqual, 2]], 
  Inequality]

True

Inactivate[
  MatchQ[
    Inequality[1, Less, x, LessEqual, 2], 
    Inequality[1, Less, _, LessEqual, 2]], 
  Inequality]

True

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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