diff --git a/core/CCLeftistheap.ml b/core/CCLeftistheap.ml index b0e5fe9f..1a73853c 100644 --- a/core/CCLeftistheap.ml +++ b/core/CCLeftistheap.ml @@ -29,6 +29,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. type 'a sequence = ('a -> unit) -> unit type 'a klist = unit -> [`Nil | `Cons of 'a * 'a klist] +type 'a gen = unit -> 'a option type 'a t = { tree : 'a tree; @@ -158,3 +159,22 @@ let to_klist h = `Cons (x, next (a :: b :: stack')) in next [h.tree] + +let rec of_gen h g = match g () with + | None -> h + | Some x -> + of_gen (add h x) g + +let to_gen h = + let stack = Stack.create () in + Stack.push h.tree stack; + let rec next () = + if Stack.is_empty stack + then None + else match Stack.pop stack with + | Empty -> next() + | Node (_, x, a, b) -> + Stack.push a stack; + Stack.push b stack; + Some x + in next diff --git a/core/CCLeftistheap.mli b/core/CCLeftistheap.mli index aa99a61f..9836ce9a 100644 --- a/core/CCLeftistheap.mli +++ b/core/CCLeftistheap.mli @@ -28,6 +28,7 @@ Polymorphic implementation, following Okasaki *) type 'a sequence = ('a -> unit) -> unit type 'a klist = unit -> [`Nil | `Cons of 'a * 'a klist] +type 'a gen = unit -> 'a option type 'a t (** Heap containing values of type 'a *) @@ -81,3 +82,6 @@ val to_seq : 'a t -> 'a sequence val of_klist : 'a t -> 'a klist -> 'a t val to_klist : 'a t -> 'a klist + +val of_gen : 'a t -> 'a gen -> 'a t +val to_gen : 'a t -> 'a gen