ygrek solution using first-class modules to decide "dynamically"
(on a boolean value) the value of the Bag
module is fine, but you can also do
that in simpler OCaml by simply defining your traversal algorithm
inside a functor taking a bag as parameter.
module type Bag =
sig
type 'a t
exception Empty
val create : unit -> 'a t
val push : 'a -> 'a t -> unit
val pop : 'a t -> 'a
val iter : ('a -> unit) -> 'a t -> unit
end
module Traversal (B : Bag) = struct
let go start children f =
let to_visit = B.create () in
B.push start to_visit;
try while true do
let next = B.pop to_visit in
f next;
let mark neighbor = B.push neighbor to_visit in
List.iter mark (children next);
done with B.Empty -> ()
end;;
(* note that "BagWrapper" is useless here as the existing modules
fit the Bag interface perfectly, there is no need for a middle
layer *)
module StackTraversal = Traversal(Stack)
module QueueTraversal = Traversal(Queue)
(* ... if foo then StackTraversal.go else QueueTraversal.go ... *)