Module R.
Inductive t : Type := Nil | Cons (lo hi: Z) (tl: t).
Fixpoint In (x: Z) (s: t) :=
match s with
| Nil => False
| Cons l h s' => l <= x < h \/ In x s'
end.
Inductive ok: t -> Prop :=
| ok_nil: ok Nil
| ok_cons: forall l h s
(BOUNDS: l < h)
(BELOW: forall x, In x s -> h < x)
(OK: ok s),
ok (Cons l h s).
Fixpoint mem (x: Z) (s: t) : bool :=
match s with
| Nil => false
| Cons l h s' => if zlt x h then zle l x else mem x s'
end.
Fixpoint contains (L H: Z) (s: t) : bool :=
match s with
| Nil => false
| Cons l h s' => (zle H h && zle l L) || contains L H s'
end.
Fixpoint add (L H: Z) (s: t) {struct s} : t :=
match s with
| Nil => Cons L H Nil
| Cons l h s' =>
if zlt h L then Cons l h (add L H s')
else if zlt H l then Cons L H s
else add (Z.min l L) (Z.max h H) s'
end.
Fixpoint remove (L H: Z) (s: t) {struct s} : t :=
match s with
| Nil => Nil
| Cons l h s' =>
if zlt h L then Cons l h (remove L H s')
else if zlt H l then s
else if zlt l L then
if zlt H h then Cons l L (Cons H h s') else Cons l L (remove L H s')
else
if zlt H h then Cons H h s' else remove L H s'
end.

Lemma remove_ok:
forall l0 h0, l0 < h0 -> forall s, ok s -> ok (remove l0 h0 s).