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