Skip to content

Instantly share code, notes, and snippets.

@Mroik
Created October 19, 2023 00:24
Show Gist options
  • Save Mroik/4136da99c757346a02d495bc1ba4a41e to your computer and use it in GitHub Desktop.
Save Mroik/4136da99c757346a02d495bc1ba4a41e to your computer and use it in GitHub Desktop.
26 Feb 2015
module type Comparable = sig
type t
val compare: t -> t -> int
val to_string: t -> string
end;;
module Interval (IType: Comparable) = struct
type endpoint = IType.t
type interval = endpoint list
exception WrongInterval
let create (start: endpoint) (finish: endpoint): interval =
if finish < start then
raise WrongInterval
else
[start; finish]
let is_empty (ii: interval): bool = List.length ii = 0
let contains (ii: interval) (x: endpoint): bool =
match ii with
| [left; right] -> left <= x && x <= right
| _ -> raise WrongInterval
let intersect (i1: interval) (i2: interval): interval =
match i1, i2 with
| [left1; right1], [left2; right2] ->
let left = max left1 left2 in
let right = min right1 right2 in
if left <= right then
[left; right]
else
[]
| _ -> raise WrongInterval
let to_string (ii: interval): string =
let ris = List.map (IType.to_string) ii
|> List.fold_left (fun acc v -> acc ^ ", " ^ v) "" in
let ris = if String.length ris > 0 then
String.sub ris 2 (String.length ris - 2)
else
ris
in
"[" ^ ris ^ "]"
end;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment