[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

Re: [Libguestfs] [PATCH 1/3] mllib: Add sort_uniq function.



On 11/18/2015 01:03 AM, Richard W.M. Jones wrote:
This is copied from supermin.
---
  mllib/common_utils.ml  | 16 ++++++++++++++++
  mllib/common_utils.mli |  6 ++++++
  2 files changed, 22 insertions(+)

diff --git a/mllib/common_utils.ml b/mllib/common_utils.ml
index 13e9256..5fb7183 100644
--- a/mllib/common_utils.ml
+++ b/mllib/common_utils.ml
@@ -267,6 +267,22 @@ let rec assoc ?(cmp = compare) ~default x = function
    | (y, y') :: _ when cmp x y = 0 -> y'
    | _ :: ys -> assoc ~cmp ~default x ys
+let uniq ?(cmp = Pervasives.compare) xs =
+  let rec loop acc = function
+    | [] -> acc
+    | [x] -> x :: acc
+    | x :: (y :: _ as xs) when cmp x y = 0 ->
+       loop acc xs
+    | x :: (y :: _ as xs) ->
+       loop (x :: acc) xs
+  in
+  List.rev (loop [] xs)
+
+let sort_uniq ?(cmp = Pervasives.compare) xs =
+  let xs = List.sort cmp xs in
+  let xs = uniq ~cmp xs in
+  xs
+
  let may f = function
    | None -> ()
    | Some x -> f x
diff --git a/mllib/common_utils.mli b/mllib/common_utils.mli
index 44b8c93..68f7988 100644
--- a/mllib/common_utils.mli
+++ b/mllib/common_utils.mli
@@ -124,6 +124,12 @@ val assoc : ?cmp:('a -> 'a -> int) -> default:'b -> 'a -> ('a * 'b) list -> 'b
  (** Like {!List.assoc} but with a user-defined comparison function, and
      instead of raising [Not_found], it returns the [~default] value. *)
+val uniq : ?cmp:('a -> 'a -> int) -> 'a list -> 'a list
+  (** Uniquify a list (the list must be sorted first). *)
+
+val sort_uniq : ?cmp:('a -> 'a -> int) -> 'a list -> 'a list
+  (** Sort and uniquify a list. *)
+
  val may : ('a -> unit) -> 'a option -> unit
  (** [may f (Some x)] runs [f x].  [may f None] does nothing. *)
adding roman to CC:


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]