# Strange behavior with Inequality and pattern matching

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)?

• 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. – march Mar 8 '16 at 18:41
• – Michael E2 Mar 8 '16 at 18:55

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 *)


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]


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