diff --git a/Makefile b/Makefile index 9b704d54..5ce97aad 100644 --- a/Makefile +++ b/Makefile @@ -4,6 +4,7 @@ IMPLEMENTATION_FILES = $(shell find -name '*.ml') TARGETS_LIB = containers.cmxa containers.cma TARGET_THREAD_LIB = thread_containers.cmxa thread_containers.cma +EXAMPLES = examples/mem_size.native examples/collatz.native OPTIONS = -use-ocamlfind all: lib lib_thread @@ -14,8 +15,8 @@ lib: lib_thread: ocamlbuild $(OPTIONS) $(TARGETS_LIB) $(TARGET_THREAD_LIB) -examples: - ocamlbuild $(OPTIONS) -I . examples/mem_size.native +examples: all + ocamlbuild $(OPTIONS) -I . $(EXAMPLES) tests: ocamlbuild $(OPTIONS) -package oUnit -I . tests/run_tests.native diff --git a/examples/collatz.ml b/examples/collatz.ml new file mode 100644 index 00000000..47b78aea --- /dev/null +++ b/examples/collatz.ml @@ -0,0 +1,20 @@ + +(** Display the graph of the collatz conjecture, starting from the given int *) + +let g = LazyGraph.map + ~edges:(fun () -> []) + ~vertices:(fun i -> [`Label (string_of_int i)]) + LazyGraph.collatz_graph + +let collatz n filename = + Format.printf "print graph to %s@." filename; + let out = open_out filename in + let fmt = Format.formatter_of_out_channel out in + LazyGraph.Dot.pp ~name:"collatz" g fmt (Enum.singleton n); + Format.pp_print_flush fmt (); + close_out out + +let _ = + if Array.length Sys.argv < 3 + then (Format.printf "use: collatz num file@."; exit 0) + else collatz (int_of_string Sys.argv.(1)) Sys.argv.(2) diff --git a/lazyGraph.ml b/lazyGraph.ml index 6d81470d..fbbe49a1 100644 --- a/lazyGraph.ml +++ b/lazyGraph.ml @@ -390,3 +390,29 @@ module Dot = struct let enum = Full.bfs_full graph vertices in pp_enum ~eq:graph.eq ~hash:graph.hash ~name formatter enum end + +(** {2 Example of graphs} *) + +let divisors_graph = + let rec divisors acc j i = + if j = i then acc + else + let acc' = if (i mod j = 0) then j :: acc else acc in + divisors acc' (j+1) i + in + let force i = + if i > 2 + then + let l = divisors [] 2 i in + let edges = Enum.map (fun i -> (), i) (Enum.of_list l) in + Node (i, i, edges) + else + Node (i, i, Enum.empty) + in make force + +let collatz_graph = + let force i = + if i mod 2 = 0 + then Node (i, i, Enum.singleton ((), i / 2)) + else Node (i, i, Enum.singleton ((), i * 3 + 1)) + in make force diff --git a/lazyGraph.mli b/lazyGraph.mli index 893999b7..744f7db5 100644 --- a/lazyGraph.mli +++ b/lazyGraph.mli @@ -207,3 +207,9 @@ module Dot : sig (** Pretty print the given graph (starting from the given set of vertices) to the channel in DOT format *) end + +(** {2 Example of graphs} *) + +val divisors_graph : (int, int, unit) t + +val collatz_graph : (int, int, unit) t