Skip to content

Instantly share code, notes, and snippets.

@samebchase
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samebchase/11382809 to your computer and use it in GitHub Desktop.
Save samebchase/11382809 to your computer and use it in GitHub Desktop.
Learning how to use the ocamlgraph library
open Graph
module Vertex = struct
type t = string
let compare = Pervasives.compare
let hash = Hashtbl.hash
let equal = (=)
end
module Edge = struct
type t = int
let compare = Pervasives.compare
let default = 1
end
module Weight = struct
type label = int
type t = int
let weight x = x
let compare = Pervasives.compare
let add = (+)
let zero = 0
end
module G = Imperative.Graph.ConcreteLabeled(Vertex)(Edge)
module Dij = Path.Dijkstra(G)(Weight)
let word_graph = G.create ()
let load_graph () =
List.iter ["one";"two";"three";"four"] ~f:(fun str -> G.add_vertex word_graph (G.V.create str));
G.add_edge_e word_graph (G.E.create "one" 1 "two");
G.add_edge_e word_graph (G.E.create "two" 1 "three");
G.add_edge_e word_graph (G.E.create "three" 1 "four");
;;
let () =
load_graph ();
List.iter (fst (Dij.shortest_path word_graph "one" "four"))
~f:(fun edge ->
match edge with
(src, _weight, dest) ->
Core.Std.printf "%s -> %s, " src dest;)
;;
(*
$ corebuild -pkg extlib,core,ocamlgraph,batteries shortest_path.byte
$ ./shortest_path.byte
one -> two, two -> three, three -> four, %
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment