# Removing an interval within another interval?

Suppose we have the interval

Interval[{-5,5}]

How do we remove an interval from within this interval?

For example, if we wanted to remove Interval[{-3,3}] from Interval[{-5,5}] we would get Interval[{-5,-3},{3,5}].

I looked in the mathematica documentations and searched through previous questions but could not find anything.

• There is a function that does that in the wolfram function repository. You can use ResourceFunction["IntervalComplement"][Interval[{-5, 5}], Interval[{-3, 3}]]. Commented Aug 20, 2022 at 2:56
• I use the wolfram website to read documentation and typing complement i found that under "Wolfram Language Documentation". I am using linux and do not have the documentation installed but maybe if you write complement in the documentation search box that function will also appear. Commented Aug 20, 2022 at 3:04
• You can also write a custom function using IntervalMemberQ first to check whether the second interval is completely contained in the first, extract the list inside Interval using Level[Interval[{-5, 5}],{2}] and then Interval @@ Partition[Sort[{-5, 5}~Join~{-3, 3}], 2]. Commented Aug 20, 2022 at 3:13
• Intervals are regions, RegionQ[Interval[{-5,5}]] yields True, but unfortunately RegionDifference[Interval[{-5,5}],Interval[{-3,3}]] does not return something useful. But Line works, try RegionDifference[Line[{{-5},{5}}],Line[{{-3},{3}}]], and one could translate from Interval to Line and back. Commented Aug 20, 2022 at 11:01

The fact that this is not built-in to Mathematica suggests that there are some non-trivial subtleties. However, I offer the following simple implementation

IntervalComplement[Interval[{a_, b_}]] :=
Interval[{-∞, a}, {b, ∞}]
IntervalComplement[Interval[a__List]] :=
IntervalIntersection @@ IntervalComplement@*Interval /@ {a}
IntervalDifference[a_Interval, b_Interval] :=
IntervalIntersection[a, IntervalComplement[b]]


Test cases

int1 = Interval[{-5, 5}];
int2 = Interval[{-3, 3}];
int3 = Interval[{-5, -3}, {3, 5}];
IntervalComplement /@ {int1, int2, int3}
(* {Interval[{-∞, -5}, {5, ∞}],
Interval[{-∞, -3}, {3, ∞}],
Interval[{-∞, -5}, {-3, 3}, {5, ∞}]} *)


IntervalDifference[int1, int2] == int3