psss / rpms / libguestfs

Forked from rpms/libguestfs 5 years ago
Clone
Blob Blame History Raw
From f57dc38c05f3b8b002b8daa823a21ad25f5d682d Mon Sep 17 00:00:00 2001
From: "Richard W.M. Jones" <rjones@redhat.com>
Date: Tue, 10 Nov 2015 20:07:56 +0000
Subject: [PATCH 2/5] mllib: Add Common_utils 'may' function.

This higher order function encapsulates the following pattern:

  match x with
  | None -> ()
  | Some x -> f x

(replaced with: `may f x`)

This is taken from OCaml lablgtk (Gtk bindings) where this pattern is
used frequently.

See also: https://ocaml.org/learn/tutorials/labels.html

(cherry picked from commit 9a2c5b7c4d367aae665ab66f85e463f9d244e465)
---
 mllib/common_utils.ml  | 4 ++++
 mllib/common_utils.mli | 3 +++
 2 files changed, 7 insertions(+)

diff --git a/mllib/common_utils.ml b/mllib/common_utils.ml
index c714cb3..dfee615 100644
--- a/mllib/common_utils.ml
+++ b/mllib/common_utils.ml
@@ -254,6 +254,10 @@ let rec assoc ?(cmp = compare) ~default x = function
   | (y, y') :: _ when cmp x y = 0 -> y'
   | _ :: ys -> assoc ~cmp ~default x ys
 
+let may f = function
+  | None -> ()
+  | Some x -> f x
+
 let istty chan =
   Unix.isatty (Unix.descr_of_out_channel chan)
 
diff --git a/mllib/common_utils.mli b/mllib/common_utils.mli
index 39e05a1..081e4a4 100644
--- a/mllib/common_utils.mli
+++ b/mllib/common_utils.mli
@@ -65,6 +65,9 @@ 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 may : ('a -> unit) -> 'a option -> unit
+(** [may f (Some x)] runs [f x].  [may f None] does nothing. *)
+
 val prog : string
 (** The program name (derived from {!Sys.executable_name}). *)
 
-- 
2.5.0