.
[SXSI/xpathcomp.git] / hlist.ml
1 INCLUDE "utils.ml"
2 module type S = sig
3   type elt 
4   type 'a node = Nil | Cons of elt * 'a
5
6   module rec Node : 
7   sig
8     include Hcons.S with type data = Data.t
9   end
10   and Data : sig
11     include Hashtbl.HashedType with type t = Node.t node
12   end
13   type data = Data.t
14   type t = Node.t
15   val hash : t -> int
16   val uid : t -> Uid.t
17   val make : data -> t
18   val equal : t -> t -> bool
19   val nil : t
20   val node : t -> t node
21   val cons : elt -> t -> t
22   val hd : t -> elt
23   val tl : t -> t
24   val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
25   val map : (elt -> elt) -> t -> t
26   val iter : (elt -> 'a) -> t -> unit
27   val rev : t -> t
28   val rev_map : (elt -> elt) -> t -> t
29   val length : t -> int
30
31   val with_id : Uid.t -> t
32 end
33
34 module Make ( H : Hcons.SA ) : S with type elt = H.t =
35 struct
36   type elt = H.t
37   type 'a node = Nil | Cons of elt * 'a
38   module rec Node : Hcons.S with type data = Data.t = Hcons.Make (Data)
39   and Data : Hashtbl.HashedType  with type t = Node.t node =
40   struct 
41     type t = Node.t node
42     let equal x y = 
43       match x,y with
44         | _,_ when x==y -> true
45         | Cons (a,aa), Cons(b,bb) -> (aa==bb) && (H.equal a b)
46         | _ -> false
47     let hash = function 
48       | Nil -> 0
49       | Cons(a,aa) -> HASHINT3(PRIME3,Uid.to_int (H.uid a),Uid.to_int( aa.Node.id))
50   end
51   type data = Data.t
52   type t = Node.t
53   let make = Node.make
54   let node x = x.Node.node
55   let hash x = x.Node.key
56   let equal = Node.equal
57   let uid x= x.Node.id
58   let nil = Node.make Nil
59   let cons a b = Node.make (Cons(a,b))
60   let hd = function { Node.node = Cons(a,_) } -> a | _ -> failwith "hd"
61   let tl = function { Node.node = Cons(_,a) } -> a | _ -> failwith "tl"
62
63   let fold f l acc =
64     let rec loop acc l = match l.Node.node with
65       | Nil -> acc
66       | Cons(a,aa) -> loop (f a acc) aa
67     in
68       loop acc l
69         
70   let map f l  =
71     let rec loop l = match l.Node.node with
72       | Nil -> nil
73       | Cons(a,aa) -> cons (f a) (loop aa)
74     in
75       loop l
76
77   let iter f l = 
78     let rec loop l = match l.Node.node with
79       | Nil -> ()
80       | Cons(a,aa) ->  (f a);(loop aa)
81     in
82       loop l
83         
84   let rev l = fold cons l nil
85   let rev_map f l = fold (fun x acc -> cons (f x) acc) l nil
86   let length l = fold (fun _ c -> c+1) l 0 
87     
88
89   let with_id = Node.with_id
90 end