add basic mutable graphs

This commit is contained in:
Simon Cruanes 2015-06-10 18:02:09 +02:00
parent eed339463d
commit 1586558e6f
2 changed files with 48 additions and 2 deletions

View file

@ -30,6 +30,8 @@ type 'a sequence_once = 'a sequence
exception Sequence_once
let (|>) x f = f x
module Seq = struct
type 'a t = 'a sequence
let return x k = k x
@ -44,8 +46,6 @@ module Seq = struct
let to_list seq = fold (fun acc x->x::acc) [] seq |> List.rev
end
let (|>) x f = f x
(** {2 Interfaces for graphs} *)
(** Directed graph with vertices of type ['v] and edges of type [e'] *)
@ -594,6 +594,38 @@ module Dot = struct
raise e
end
(** {2 Mutable Graph} *)
type ('v, 'e) mut_graph = <
graph: ('v, 'e) t;
add_edge: 'e -> unit;
remove : 'v -> unit;
>
let mk_mut_tbl (type k) ?(eq=(=)) ?(hash=Hashtbl.hash) size =
let module Tbl = Hashtbl.Make(struct
type t = k
let hash = hash
let equal = eq
end) in
let tbl = Tbl.create size in
object
method graph = {
origin=(fun (x,_,_) -> x);
dest=(fun (_,_,x) -> x);
children=(fun v k ->
try List.iter k (Tbl.find tbl v)
with Not_found -> ()
);
}
method add_edge (v1,e,v2) =
let l = try Tbl.find tbl v1 with Not_found -> [] in
Tbl.replace tbl v1 ((v1,e,v2)::l)
method remove v = Tbl.remove tbl v
end
(** {2 Misc} *)
let of_list ?(eq=(=)) l = {
origin=fst;
dest=snd;

View file

@ -305,6 +305,20 @@ module Dot : sig
(** Shortcut to open a file and write to it *)
end
(** {2 Mutable Graph} *)
type ('v, 'e) mut_graph = <
graph: ('v, 'e) t;
add_edge: 'e -> unit;
remove : 'v -> unit;
>
val mk_mut_tbl : ?eq:('v -> 'v -> bool) ->
?hash:('v -> int) ->
int ->
('v, ('v * 'a * 'v)) mut_graph
(** make a new mutable graph from a Hashtbl. Edges are labelled with type ['a] *)
(** {2 Misc} *)
val of_list : ?eq:('v -> 'v -> bool) -> ('v * 'v) list -> ('v, ('v * 'v)) t