Fix the build script.
[tatoo.git] / src / utils / hlist.ml
1 INCLUDE "utils.ml"
2
3 include Hlist_sig
4
5 module type HConsBuilder =
6   functor (H : Common_sig.HashedType) -> Hcons.S with type data = H.t
7
8 module Builder (HCB : HConsBuilder) (H : Hcons.Abstract) :
9   S with type elt = H.t =
10 struct
11   type elt = H.t
12
13   module rec Node : Hcons.S with type data = Data.t = HCB(Data)
14                             and Data : Common_sig.HashedType with type t = (elt, Node.t) node =
15   struct
16     type t = (elt, Node.t) node
17     let equal x y =
18       match x,y with
19       | Nil, Nil -> true
20       | Cons(e1, l1), Cons(e2, l2) -> e1 == e2 && l1 == l2
21       | _ -> false
22
23     let hash = function
24     | Nil -> 0
25     | Cons(e, l) -> HASHINT3 (PRIME1, Uid.to_int (H.uid e), Uid.to_int (Node.uid l))
26   end
27
28   include Node
29
30   let nil = make Nil
31
32   let rec sorted_cons e l =
33     match l.Node.node with
34       | Nil -> Node.make (Cons(e, l))
35       | Cons (x, ll) ->
36           if H.uid e < H.uid x
37           then Node.make (Cons(e, l))
38           else Node.make (Cons(x, sorted_cons e ll))
39
40   let cons e l =
41     Node.make(Cons(e, l))
42
43   let cons ?(sorted=true) e l =
44     if sorted then sorted_cons e l else cons e l
45
46   let hd = function { Node.node = Cons(e, _); _ } -> e | _ -> failwith "hd"
47   let tl = function { Node.node = Cons(_, l); _ } -> l | _ -> failwith "tl"
48
49   let fold f l acc =
50     let rec loop acc l = match l.Node.node with
51       | Nil -> acc
52       | Cons (a, aa) -> loop (f a acc) aa
53     in
54       loop acc l
55
56   let map f l  =
57     let rec loop l = match l.Node.node with
58       | Nil -> nil
59       | Cons(a, aa) -> cons (f a) (loop aa)
60     in
61       loop l
62
63   let iter f l =
64     let rec loop l = match l.Node.node with
65       | Nil -> ()
66       | Cons(a,aa) ->  (f a);(loop aa)
67     in
68       loop l
69
70   let rev l = fold cons l nil
71   let rev_map f l = fold (fun x acc -> cons (f x) acc) l nil
72   let length l = fold (fun _ c -> c+1) l 0
73   let rec mem e l =
74     match l.Node.node with
75       | Nil -> false
76       | Cons (x, ll) -> x == e || mem e ll
77
78 end
79
80 module Make = Builder(Hcons.Make)
81 module Weak = Builder(Hcons.Weak)
82