10
0
mirror of https://github.com/LCPQ/quantum_package synced 2024-11-05 13:43:57 +01:00
quantum_package/ocaml/Range.ml

80 lines
1.9 KiB
OCaml
Raw Normal View History

2017-08-18 19:43:52 +02:00
open Sexplib.Std
2014-08-26 15:31:16 +02:00
(* A range is a string of the type:
*
* "[36-53,72-107,126-131]"
*
* that should represent the list of integers
* [ 37 ; 37 ; 38 ; ... ; 52 ; 53 ; 72 ; 73 ; ... ; 106 ; 107 ; 126 ; 127 ; ...
* ; 130 ; 131 ]
*
* or it can be an integer
2014-08-26 15:31:16 +02:00
*)
2017-08-18 19:43:52 +02:00
type t = int list [@@deriving sexp]
2014-08-26 15:31:16 +02:00
let expand_range r =
2017-08-18 19:43:52 +02:00
match String_ext.lsplit2 ~on:'-' r with
2014-08-26 15:31:16 +02:00
| Some (s, f) ->
begin
2017-08-18 19:43:52 +02:00
let start = int_of_string s
and finish = int_of_string f
2014-08-26 15:31:16 +02:00
in
assert (start <= finish) ;
let rec do_work = function
| i when i=finish -> [ i ]
| i -> i::(do_work (i+1))
in do_work start
end
| None ->
begin
match r with
| "" -> []
2017-08-18 19:43:52 +02:00
| _ -> [int_of_string r]
2014-08-26 15:31:16 +02:00
end
2017-08-18 19:43:52 +02:00
2014-08-26 15:31:16 +02:00
let of_string s =
match s.[0] with
| '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ->
[ int_of_string s ]
| _ ->
assert (s.[0] = '[') ;
assert (s.[(String.length s)-1] = ']') ;
let s = String.sub s 1 ((String.length s) - 2) in
2017-08-18 19:43:52 +02:00
let l = String_ext.split ~on:',' s in
let l = List.map expand_range l in
List.concat l
|> List.sort_uniq compare
2014-08-26 15:31:16 +02:00
let to_string l =
let rec do_work buf symbol = function
| [] -> buf
| a::([] as t) ->
2017-08-18 19:43:52 +02:00
do_work (buf^symbol^(string_of_int a)) "" t
2014-08-26 15:31:16 +02:00
| a::(b::q as t) ->
if (b-a = 1) then
do_work buf "-" t
else
2017-08-18 19:43:52 +02:00
do_work (buf^symbol^(string_of_int a)^","^(string_of_int b)) "" t
2014-08-26 15:31:16 +02:00
in
let result =
match l with
| [] ->
"[]"
| h::t ->
2017-08-18 19:43:52 +02:00
do_work ("["^(string_of_int h)) "" l in
2014-08-26 15:31:16 +02:00
(String.sub result 0 ((String.length result)))^"]"
2017-08-18 19:43:52 +02:00
2014-08-26 15:31:16 +02:00
let test_module () =
let s = "[72-107,36-53,126-131]" in
let l = of_string s in
2017-08-18 19:43:52 +02:00
print_string s ; print_newline () ;
List.iter (fun x -> Printf.printf "%d, " x) l ; print_newline () ;
to_string l |> print_string ; print_newline ();
2014-08-26 15:31:16 +02:00