From 7dbf3f983baad5c64fab383f6564d44904bcd092 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Mon, 25 Jan 2016 16:38:36 +0100 Subject: [PATCH] add `CCFun.finally{1,2}`, convenience around `finally` --- src/core/CCFun.cppo.ml | 22 ++++++++++++++++++++-- src/core/CCFun.mli | 14 ++++++++++++-- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/core/CCFun.cppo.ml b/src/core/CCFun.cppo.ml index 77f12094..a1fad6ed 100644 --- a/src/core/CCFun.cppo.ml +++ b/src/core/CCFun.cppo.ml @@ -64,10 +64,28 @@ let lexicographic f1 f2 x y = let finally ~h ~f = try let x = f () in - h (); + ignore (h ()); x with e -> - h (); + ignore (h ()); + raise e + +let finally1 ~h f x = + try + let res = f x in + ignore (h ()); + res + with e -> + ignore (h ()); + raise e + +let finally2 ~h f x y = + try + let res = f x y in + ignore (h ()); + res + with e -> + ignore (h ()); raise e module Monad(X : sig type t end) = struct diff --git a/src/core/CCFun.mli b/src/core/CCFun.mli index b6abcf08..ab609916 100644 --- a/src/core/CCFun.mli +++ b/src/core/CCFun.mli @@ -57,7 +57,7 @@ val curry : ('a * 'b -> 'c) -> 'a -> 'b -> 'c val uncurry : ('a -> 'b -> 'c) -> ('a * 'b) -> 'c -val tap : ('a -> 'b) -> 'a -> 'a +val tap : ('a -> _) -> 'a -> 'a (** [tap f x] evaluates [f x], discards it, then returns [x]. Useful in a pipeline, for instance: {[CCArray.(1 -- 10) @@ -72,11 +72,21 @@ val (%) : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c val lexicographic : ('a -> 'a -> int) -> ('a -> 'a -> int) -> 'a -> 'a -> int (** Lexicographic combination of comparison functions *) -val finally : h:(unit -> unit) -> f:(unit -> 'a) -> 'a +val finally : h:(unit -> _) -> f:(unit -> 'a) -> 'a (** [finally h f] calls [f ()] and returns its result. If it raises, the same exception is raised; in {b any} case, [h ()] is called after [f ()] terminates. *) +val finally1 : h:(unit -> _) -> ('a -> 'b) -> 'a -> 'b +(** [finally1 ~h f x] is the same as [f x], but after the computation, + [h ()] is called whether [f x] rose an exception or not. + @since NEXT_RELEASE *) + +val finally2 : h:(unit -> _) -> ('a -> 'b -> 'c) -> 'a -> 'b -> 'c +(** [finally2 ~h f x y] is the same as [f x y], but after the computation, + [h ()] is called whether [f x y] rose an exception or not. + @since NEXT_RELEASE *) + (** {2 Monad} Functions with a fixed domain are monads in their codomain *)