Fixed bug in NextElement, improved caching
[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 -> int
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 end
31
32 module Make ( H : Hcons.SA ) : S with type elt = H.t =
33 struct
34   type elt = H.t
35   type 'a node = Nil | Cons of elt * 'a
36   module rec Node : Hcons.S with type data = Data.t = Hcons.Make (Data)
37   and Data : Hashtbl.HashedType  with type t = Node.t node =
38   struct 
39     type t = Node.t node
40     let equal x y = 
41       match x,y with
42         | _,_ when x==y -> true
43         | Cons (a,aa), Cons(b,bb) -> (aa==bb) && (H.equal a b)
44         | _ -> false
45     let hash = function 
46       | Nil -> 0
47       | Cons(a,aa) -> HASHINT3(PRIME3,H.uid a, aa.Node.id)
48   end
49   type data = Data.t
50   type t = Node.t
51   let make = Node.make
52   let node x = x.Node.node
53   let hash x = x.Node.key
54   let equal = Node.equal
55   let uid x= x.Node.id
56   let nil = Node.make Nil
57   let cons a b = Node.make (Cons(a,b))
58   let hd = function { Node.node = Cons(a,_) } -> a | _ -> failwith "hd"
59   let tl = function { Node.node = Cons(_,a) } -> a | _ -> failwith "tl"
60
61   let fold f l acc =
62     let rec loop acc l = match l.Node.node with
63       | Nil -> acc
64       | Cons(a,aa) -> loop (f a acc) aa
65     in
66       loop acc l
67         
68   let map f l  =
69     let rec loop l = match l.Node.node with
70       | Nil -> nil
71       | Cons(a,aa) -> cons (f a) (loop aa)
72     in
73       loop l
74
75   let iter f l = 
76     let rec loop l = match l.Node.node with
77       | Nil -> ()
78       | Cons(a,aa) ->  (f a);(loop aa)
79     in
80       loop l
81         
82   let rev l = fold cons l nil
83   let rev_map f l = fold (fun x acc -> cons (f x) acc) l nil
84   let length l = fold (fun _ c -> c+1) l 0 
85 end