Advertisement
raedr7n

interval thing

Aug 21st, 2022 (edited)
1,424
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.43 KB | None | 0 0
  1. type ('a, 'b) choice = Left of 'a | Right of 'b
  2.  
  3. type debut = Debut of float
  4. type fin = Fin of float
  5.  
  6. let cmp a b =
  7.   match a, b with
  8.   | Left (Debut x), Left (Debut y)
  9.   | Left (Debut x), Right (Fin y)
  10.   | Right (Fin x), Left (Debut y)
  11.   | Right (Fin x), Right (Fin y) -> Float.compare x y
  12.  
  13. type interval = Interval of debut * fin
  14.  
  15. let rec explode is =
  16.   match is with
  17.   | [] -> []
  18.   | Interval (d, f) :: is -> [Left d; Right f] @ explode is
  19.  
  20. let mesh iss = List.sort cmp (List.fold_left (fun acc elem -> explode elem @ acc) [] iss)
  21.  
  22. let rec combine' n m depth mesh =
  23.   match mesh with
  24.   | [] -> []
  25.   | Left (Debut x' as x) :: xs ->
  26.     if depth = n - 1 then
  27.       Left x :: combine' n m (depth + 1) xs
  28.     else if depth = m then
  29.       Right (Fin x') :: combine' n m (depth + 1) xs
  30.     else
  31.       combine' n m (depth + 1) xs
  32.   | Right (Fin x' as x) :: xs ->
  33.     if depth = n then
  34.       Right x :: combine' n m (depth - 1) xs
  35.     else if depth = m + 1 then
  36.       Left (Debut x') :: combine' n m (depth - 1) xs
  37.     else
  38.       combine' n m (depth - 1) xs
  39.  
  40. let rec mkintervals mesh =
  41.   match mesh with
  42.   | [] -> []
  43.   | Left d :: Right f :: delims -> Interval (d, f) :: mkintervals delims
  44.   | _ -> failwith "IMPOSSIBLE!!!"
  45.  
  46. (* This is the main function. n and m are optional parameters, where n is the lower bound and m the upper. *)
  47. let combine ?(n = 1) ?(m = Int.max_int) iss = mkintervals (combine' n m 0 (mesh iss))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement