Advertisement
Guest User

Untitled

a guest
Nov 28th, 2016
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.33 KB | None | 0 0
  1. module type Comparable = sig
  2.     type t
  3.     val compare : t -> t -> int
  4.   end
  5.  
  6.  
  7. module Make_interval(Endpoint : Comparable) = struct
  8.  
  9.     type t = | Interval of Endpoint.t * Endpoint.t
  10.              | Empty
  11.  
  12.     (** [create low high] creates a new interval from [low] to
  13.         [high].  If [low > high], then the interval is empty *)
  14.     let create low high =
  15.       if Endpoint.compare low high > 0 then Empty
  16.       else Interval (low,high)
  17.  
  18.     (** Returns true iff the interval is empty *)
  19.     let is_empty = function
  20.       | Empty -> true
  21.       | Interval _ -> false
  22.  
  23.     (** [contains t x] returns true iff [x] is contained in the
  24.         interval [t] *)
  25.     let contains t x =
  26.       match t with
  27.       | Empty -> false
  28.       | Interval (l,h) ->
  29.         Endpoint.compare x l >= 0 && Endpoint.compare x h <= 0
  30.  
  31.     (** [intersect t1 t2] returns the intersection of the two input
  32.         intervals *)
  33.     let intersect t1 t2 =
  34.       let min x y = if Endpoint.compare x y <= 0 then x else y in
  35.       let max x y = if Endpoint.compare x y >= 0 then x else y in
  36.       match t1,t2 with
  37.       | Empty, _ | _, Empty -> Empty
  38.       | Interval (l1,h1), Interval (l2,h2) ->
  39.         create (max l1 l2) (min h1 h2)
  40.   end
  41.  
  42. module Int_interval =
  43.     Make_interval(struct
  44.       type t = int
  45.       let compare = Int.compare
  46.     end)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement