Source

ocaml-lib / common.ml

Diff from to

File common.ml

     | None::l -> filter l
     | Some x::l -> x::filter l
 
+let rec remove_first : 'a -> 'a list -> 'a list =
+  fun e -> function
+    | [] -> []
+    | x::l ->
+	if x = e
+	then l
+	else x::remove_first e l
+
 let rec mapfilter : ('a -> 'b option) -> 'a list -> 'b list =
   fun f -> function
       [] -> []
     | [] -> []
     | x::xs -> sub_list xs (pos-1) len
 
+let rec list_set_nth l n x =
+  match l with
+  | [] -> invalid_arg "Common.list_set_nth"
+  | e::l' ->
+      if n = 0
+      then x::l'
+      else e::list_set_nth l' (n-1) x
+
+let rec list_insert_nth l n l1 =
+  match l with
+  | [] -> invalid_arg "Common.list_insert_nth"
+  | e::l' ->
+      if n = 0
+      then l1 @ l'
+      else e :: list_insert_nth l' (n-1) l1
+
+let rec list_remove_nth l n =
+  match l with
+  | [] -> invalid_arg "Common.list_remove_nth"
+  | e::l' ->
+      if n = 0
+      then l'
+      else e::list_remove_nth l' (n-1)
+
+let list_n n =
+  let aux i acc =
+    if i = 0
+    then acc
+    else aux (i-1) ((i-1)::acc)
+  in
+  aux n []
+
+let rec list_index i = function
+  | [] -> []
+  | x::l -> (i,x)::list_index (i+1) l
 
 (* utilities on streams *)
 
 
 (* for profiling *)
 
-let tbl_prof : (string,(int * float * float)) Hashtbl.t = Hashtbl.create 100
+type prof_elem = {mutable prof_on : bool; mutable prof_nb : int; mutable prof_time : float; mutable prof_mem : float}
+let tbl_prof : (string, prof_elem) Hashtbl.t = Hashtbl.create 100
 
 let prof : string -> (unit -> 'a) -> 'a =
   fun s f -> (* f () *)
+    let elem =
+      try Hashtbl.find tbl_prof s
+      with Not_found ->
+	let elem = {prof_on = false; prof_nb = 0; prof_time = 0.; prof_mem = 0.} in
+	Hashtbl.add tbl_prof s elem;
+	elem in
+    let on = elem.prof_on in
 (* print_string ("<"^s^":"); flush stdout; *)
+    elem.prof_on <- true;
     let m1 = Gc.allocated_bytes () (* float_of_int (Gc.stat ()).Gc.live_words *) in
     let d, y = chrono f in
     let m2 = Gc.allocated_bytes () (* float_of_int (Gc.stat ()).Gc.live_words *) in
-    let n, t, m = try Hashtbl.find tbl_prof s with Not_found -> 0, 0., 0. in
-    Hashtbl.replace tbl_prof s (n+1, t +. d, m +. (m2 -. m1));
+    elem.prof_on <- on;
+    elem.prof_nb <- elem.prof_nb + 1;
+    if not on then elem.prof_time <- elem.prof_time +. d;
+    if not on then elem.prof_mem <- elem.prof_mem +. (m2 -. m1);
 (* print_string (s^">\n"); flush stdout; *)
     y