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
---
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 d654fa8..52079d2 100644
--- a/mllib/common_utils.ml
+++ b/mllib/common_utils.ml
@@ -267,6 +267,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 6e08e43..d8f63d5 100644
--- a/mllib/common_utils.mli
+++ b/mllib/common_utils.mli
@@ -124,6 +124,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