1 (* Function composition *)
2 let (++) f g x = f (g x);;
5 let rec aux n = function
6 | [] -> raise Not_found
7 | x::_ when p x -> n, x
8 | _::xs -> aux (n+1) xs
12 let option_map f = function
14 | Some x -> Some (f x)
17 let option_get = function
19 | None -> failwith "option_get: None"
28 | Some _ as res -> res
30 let rec index_of ?(eq=(=)) x =
33 | y::_ when eq x y -> 0
34 | _::l -> 1 + index_of ~eq x l
36 let index_of_opt ?eq l t =
38 Some (index_of ?eq t l)
43 let rec filter_map f =
48 None -> filter_map f tl
49 | Some x -> x::filter_map f tl
52 (* the input must be sorted *)
53 let rec first_duplicate =
57 | x::y::_ when x=y -> Some x
58 | _::tl -> first_duplicate tl
60 (* the input must be sorted
61 output: list of non duplicates; list of duplicates *)
62 let rec split_duplicates =
67 let nondup,dup = split_duplicates tl in
69 List.filter ((<>) x) nondup, x::dup
73 (* Non c'e' nella vecchia versione di OCaml :( *)
74 let uniq ?(compare=compare) =
75 let rec aux = function
78 | t1 :: (t2 :: _ as ts) ->
79 if compare t1 t2 = 0 then aux ts else t1 :: (aux ts)
82 let sort_uniq ?(compare=compare) l = uniq ~compare (List.sort compare l)
84 let rec list_cut = function
86 | n, x::xs -> let a, b = list_cut (n-1,xs) in x::a, b
90 let concat_map f l = List.concat (List.map f l);;
94 | [] -> assert (n = 0); []
96 | x::xs -> x::(take (n-1) xs)
102 let string_of_var v =
104 then "`" ^ string_of_int v
105 else String.make 1 (char_of_int (v + int_of_char 'a'))
108 let var_of_string s =
109 if String.length s <> 1 then (
110 if s.[0] = '`' then int_of_string (String.sub s 1 (-1 + String.length s)) else assert false
111 ) else int_of_char s.[0] - int_of_char 'a'
116 else if n < 0 then "c" ^ string_of_int n
117 else if n >= List.length l then "x" ^ string_of_int (List.length l - n - 1) else List.nth l n