[Libguestfs] [PATCH 1/3] mllib: Add a better List.assoc function.

Richard W.M. Jones rjones at redhat.com
Wed Jan 28 14:25:36 UTC 2015


You can specify what comparison function is used; and instead of
having it raise 'Not_found', it returns a ~default value.
---
 mllib/common_utils.ml  | 5 +++++
 mllib/common_utils.mli | 4 ++++
 sysprep/main.ml        | 3 +--
 3 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/mllib/common_utils.ml b/mllib/common_utils.ml
index 7a8d8a2..d4994cf 100644
--- a/mllib/common_utils.ml
+++ b/mllib/common_utils.ml
@@ -241,6 +241,11 @@ let rec combine3 xs ys zs =
   | x::xs, y::ys, z::zs -> (x, y, z) :: combine3 xs ys zs
   | _ -> invalid_arg "combine3"
 
+let rec assoc ?(cmp = compare) ~default x = function
+  | [] -> default
+  | (y, y') :: _ when cmp x y = 0 -> y'
+  | _ :: ys -> assoc ~cmp ~default x ys
+
 let istty chan =
   Unix.isatty (Unix.descr_of_out_channel chan)
 
diff --git a/mllib/common_utils.mli b/mllib/common_utils.mli
index adb436d..ccb2e5f 100644
--- a/mllib/common_utils.mli
+++ b/mllib/common_utils.mli
@@ -58,6 +58,10 @@ val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list
 val combine3 : 'a list -> 'b list -> 'c list -> ('a * 'b * 'c) list
 (** Like {!List.combine} but for triples.  All lists must be the same length. *)
 
+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 make_message_function : quiet:bool -> ('a, unit, string, unit) format4 -> 'a
 (** Timestamped progress messages.  Used for ordinary messages when
     not [--quiet]. *)
diff --git a/sysprep/main.ml b/sysprep/main.ml
index 249800f..8df8db5 100644
--- a/sysprep/main.ml
+++ b/sysprep/main.ml
@@ -230,8 +230,7 @@ read the man page virt-sysprep(1).
     let mount_opts = !mount_opts in
     let mount_opts =
       List.map (string_split ":") (string_nsplit ";" mount_opts) in
-    let mount_opts mp =
-      try List.assoc mp mount_opts with Not_found -> "" in
+    let mount_opts mp = assoc ~default:"" mp mount_opts in
 
     let msg fs = make_message_function ~quiet fs in
     msg (f_"Examining the guest ...");
-- 
2.1.0




More information about the Libguestfs mailing list