Cosmetic changes (truncate long lines, remove trailing spaces…)
[tatoo.git] / src / 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
15                                        with type t = (elt, Node.t) node
16     =
17   struct
18     type t = (elt, Node.t) node
19     let equal x y =
20       match x,y with
21       | Nil, Nil -> true
22       | Cons(e1, l1), Cons(e2, l2) -> e1 == e2 && l1 == l2
23       | _ -> false
24
25     let hash = function
26     | Nil -> 0
27     | Cons(e, l) ->
28       HASHINT3 (PRIME1, Uid.to_int (H.uid e), Uid.to_int (Node.uid l))
29   end
30
31   include Node
32
33   let nil = make Nil
34
35   let rec sorted_cons e l =
36     match l.Node.node with
37       | Nil -> Node.make (Cons(e, l))
38       | Cons (x, ll) ->
39           if H.uid e < H.uid x
40           then Node.make (Cons(e, l))
41           else Node.make (Cons(x, sorted_cons e ll))
42
43   let cons e l =
44     Node.make(Cons(e, l))
45
46   let cons ?(sorted=true) e l =
47     if sorted then sorted_cons e l else cons e l
48
49   let hd = function { Node.node = Cons(e, _); _ } -> e | _ -> failwith "hd"
50   let tl = function { Node.node = Cons(_, l); _ } -> l | _ -> failwith "tl"
51
52   let fold f l acc =
53     let rec loop acc l = match l.Node.node with
54       | Nil -> acc
55       | Cons (a, aa) -> loop (f a acc) aa
56     in
57       loop acc l
58
59   let map f l  =
60     let rec loop l = match l.Node.node with
61       | Nil -> nil
62       | Cons(a, aa) -> cons (f a) (loop aa)
63     in
64       loop l
65
66   let iter f l =
67     let rec loop l = match l.Node.node with
68       | Nil -> ()
69       | Cons(a,aa) ->  (f a);(loop aa)
70     in
71       loop l
72
73   let rev l = fold cons l nil
74   let rev_map f l = fold (fun x acc -> cons (f x) acc) l nil
75   let length l = fold (fun _ c -> c+1) l 0
76   let rec mem e l =
77     match l.Node.node with
78       | Nil -> false
79       | Cons (x, ll) -> x == e || mem e ll
80
81 end
82
83 module Make = Builder(Hcons.Make)
84 module Weak = Builder(Hcons.Weak)