From 32a59b7982cb1f9472e7d8c0ac675ab5ac22b893 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Tue, 20 Aug 2013 12:15:35 +0200 Subject: [PATCH] added filter to leftistheap --- containers.mllib | 1 + leftistheap.ml | 10 ++++++++++ leftistheap.mli | 3 +++ 3 files changed, 14 insertions(+) diff --git a/containers.mllib b/containers.mllib index fe678cdd..7741c056 100644 --- a/containers.mllib +++ b/containers.mllib @@ -24,3 +24,4 @@ RAL MultiSet UnionFind SmallSet +Leftistheap diff --git a/leftistheap.ml b/leftistheap.ml index a5fc3e34..046079ba 100644 --- a/leftistheap.ml +++ b/leftistheap.ml @@ -79,6 +79,16 @@ let insert heap x = let tree = merge_tree heap.leq (Node (1, x, Empty, Empty)) heap.tree in { heap with tree; } +let filter heap p = + let rec filter tree p = match tree with + | Empty -> Empty + | Node (_, x, l, r) when p x -> + merge_tree heap.leq (Node (1, x, Empty, Empty)) + (merge_tree heap.leq (filter l p) (filter r p)) + | Node (_, _, l, r) -> merge_tree heap.leq (filter l p) (filter r p) + in + { heap with tree = filter heap.tree p; } + let find_min heap = match heap.tree with | Empty -> raise Not_found diff --git a/leftistheap.mli b/leftistheap.mli index 7565509a..a047e0bc 100644 --- a/leftistheap.mli +++ b/leftistheap.mli @@ -46,6 +46,9 @@ val merge : 'a t -> 'a t -> 'a t val insert : 'a t -> 'a -> 'a t (** Insert a value in the heap *) +val filter : 'a t -> ('a -> bool) -> 'a t + (** Filter values, only retaining the ones that satisfy the predicate *) + val find_min : 'a t -> 'a (** Find minimal element, or raise Not_found *)