6b51a25
From f57dc38c05f3b8b002b8daa823a21ad25f5d682d Mon Sep 17 00:00:00 2001
6b51a25
From: "Richard W.M. Jones" <rjones@redhat.com>
6b51a25
Date: Tue, 10 Nov 2015 20:07:56 +0000
6b51a25
Subject: [PATCH 2/5] mllib: Add Common_utils 'may' function.
6b51a25
6b51a25
This higher order function encapsulates the following pattern:
6b51a25
6b51a25
  match x with
6b51a25
  | None -> ()
6b51a25
  | Some x -> f x
6b51a25
6b51a25
(replaced with: `may f x`)
6b51a25
6b51a25
This is taken from OCaml lablgtk (Gtk bindings) where this pattern is
6b51a25
used frequently.
6b51a25
6b51a25
See also: https://ocaml.org/learn/tutorials/labels.html
6b51a25
6b51a25
(cherry picked from commit 9a2c5b7c4d367aae665ab66f85e463f9d244e465)
6b51a25
---
6b51a25
 mllib/common_utils.ml  | 4 ++++
6b51a25
 mllib/common_utils.mli | 3 +++
6b51a25
 2 files changed, 7 insertions(+)
6b51a25
6b51a25
diff --git a/mllib/common_utils.ml b/mllib/common_utils.ml
6b51a25
index c714cb3..dfee615 100644
6b51a25
--- a/mllib/common_utils.ml
6b51a25
+++ b/mllib/common_utils.ml
6b51a25
@@ -254,6 +254,10 @@ let rec assoc ?(cmp = compare) ~default x = function
6b51a25
   | (y, y') :: _ when cmp x y = 0 -> y'
6b51a25
   | _ :: ys -> assoc ~cmp ~default x ys
6b51a25
 
6b51a25
+let may f = function
6b51a25
+  | None -> ()
6b51a25
+  | Some x -> f x
6b51a25
+
6b51a25
 let istty chan =
6b51a25
   Unix.isatty (Unix.descr_of_out_channel chan)
6b51a25
 
6b51a25
diff --git a/mllib/common_utils.mli b/mllib/common_utils.mli
6b51a25
index 39e05a1..081e4a4 100644
6b51a25
--- a/mllib/common_utils.mli
6b51a25
+++ b/mllib/common_utils.mli
6b51a25
@@ -65,6 +65,9 @@ val assoc : ?cmp:('a -> 'a -> int) -> default:'b -> 'a -> ('a * 'b) list -> 'b
6b51a25
 (** Like {!List.assoc} but with a user-defined comparison function, and
6b51a25
     instead of raising [Not_found], it returns the [~default] value. *)
6b51a25
 
6b51a25
+val may : ('a -> unit) -> 'a option -> unit
6b51a25
+(** [may f (Some x)] runs [f x].  [may f None] does nothing. *)
6b51a25
+
6b51a25
 val prog : string
6b51a25
 (** The program name (derived from {!Sys.executable_name}). *)
6b51a25
 
6b51a25
-- 
6b51a25
2.5.0
6b51a25