]> matita.cs.unibo.it Git - fireball-separation.git/blob - ocaml/util.ml
Copy ocaml folder from sacerdot's svn repository, rev 4907
[fireball-separation.git] / ocaml / util.ml
1 (* Function composition *)
2 let (++) f g x = f (g x);;
3
4 let findi p =
5  let rec aux n = function
6  | [] -> raise Not_found
7  | x::_ when p x -> n, x
8  | _::xs -> aux (n+1) xs
9  in aux 0
10 ;;
11
12 let option_map f = function
13  | None -> None
14  | Some x -> Some (f x)
15 ;;
16
17 let rec find_opt f =
18  function
19     [] -> None
20   | x::xs ->
21      match f x with
22         None -> find_opt f xs
23       | Some _ as res -> res
24
25 let rec index_of ?(eq=(=)) x =
26  function
27     [] -> raise Not_found
28   | y::_ when eq x y -> 0
29   | _::l -> 1 + index_of ~eq x l
30
31 let index_of_opt ?eq l t =
32  try
33   Some (index_of ?eq t l)
34  with
35   Not_found -> None
36 ;;
37
38 let rec filter_map f =
39  function
40     [] -> []
41   | hd::tl ->
42      match f hd with
43         None -> filter_map f tl
44       | Some x -> x::filter_map f tl
45 ;;
46
47 (* the input must be sorted *)
48 let rec first_duplicate =
49  function
50     []
51   | [_] -> None
52   | x::y::_ when x=y -> Some x
53   | _::tl -> first_duplicate tl
54
55 (* the input must be sorted
56    output: list of non duplicates; list of duplicates *)
57 let rec split_duplicates =
58  function
59     [] -> [],[]
60   | [x] -> [x],[]
61   | x::(y::_ as tl) ->
62      let nondup,dup = split_duplicates tl in
63      if x = y then
64       List.filter ((<>) x) nondup, x::dup
65      else
66       x::nondup,dup
67
68 (* Non c'e' nella vecchia versione di OCaml :( *)
69 let uniq ?(compare=compare) =
70   let rec aux = function
71   | [] -> []
72   | [_] as ts -> ts
73   | t1 :: (t2 :: _ as ts) ->
74     if compare t1 t2 = 0 then aux ts else t1 :: (aux ts)
75   in aux
76
77 let sort_uniq ?(compare=compare) l = uniq ~compare (List.sort compare l)
78
79 let rec list_cut = function
80   | 0, lst -> [], lst
81   | n, x::xs -> let a, b = list_cut (n-1,xs) in x::a, b
82   | _ -> assert false
83 ;;
84
85 let concat_map f l = List.concat (List.map f l);;
86
87 let rec take n =
88  function
89  | [] -> assert (n = 0); []
90  | _ when n = 0 -> []
91  | x::xs -> x::(take (n-1) xs)
92 ;;
93
94 module Vars =
95 struct
96
97 let string_of_var v =
98   if v > 25
99      then "`" ^ string_of_int v
100      else String.make 1 (char_of_int (v + int_of_char 'a'))
101 ;;
102
103 let var_of_string s =
104  if String.length s <> 1 then (
105    if s.[0] = '`' then int_of_string (String.sub s 1 (-1 + String.length s)) else assert false
106  ) else int_of_char s.[0] - int_of_char 'a'
107
108 let print_name l n =
109  if n = -1
110   then "*"
111   else if n >= List.length l then "x" ^ string_of_int (List.length l - n - 1) else List.nth l n
112
113 end