From 945325054f107ad3ed6d50cf2f51ae774b63cb6b Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Tue, 3 Jun 2014 17:03:25 +0200 Subject: [PATCH] more functions for CCOpt --- core/CCOpt.ml | 16 ++++++++++++++++ core/CCOpt.mli | 13 +++++++++++++ 2 files changed, 29 insertions(+) diff --git a/core/CCOpt.ml b/core/CCOpt.ml index 7a979b62..f5e8f753 100644 --- a/core/CCOpt.ml +++ b/core/CCOpt.ml @@ -58,6 +58,10 @@ let (>>=) o f = match o with | None -> None | Some x -> f x +let flat_map f o = match o with + | None -> None + | Some x -> f x + let (<*>) f x = match f, x with | None, _ | _, None -> None @@ -70,10 +74,22 @@ let map2 f o1 o2 = match o1, o2 with | _, None -> None | Some x, Some y -> Some (f x y) +let iter f o = match o with + | None -> () + | Some x -> f x + +let fold f acc o = match o with + | None -> acc + | Some x -> f acc x + let to_list o = match o with | None -> [] | Some x -> [x] +let of_list = function + | x::_ -> Some x + | [] -> None + type 'a sequence = ('a -> unit) -> unit type 'a gen = unit -> 'a option type 'a printer = Buffer.t -> 'a -> unit diff --git a/core/CCOpt.mli b/core/CCOpt.mli index 16d96f3b..c81f0081 100644 --- a/core/CCOpt.mli +++ b/core/CCOpt.mli @@ -29,6 +29,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. type 'a t = 'a option val map : ('a -> 'b) -> 'a t -> 'b t +(** Transform the element inside, if any *) val maybe : ('a -> 'b) -> 'b -> 'a t -> 'b (** [maybe f x o] is [x] if [o] is [None], otherwise it's [f y] if [o = Some y] *) @@ -45,16 +46,28 @@ val return : 'a -> 'a t val (>>=) : 'a t -> ('a -> 'b t) -> 'b t (** Monadic bind *) +val flat_map : ('a -> 'b t) -> 'a t -> 'b t +(** Flip version of {!>>=} *) + val (<*>) : ('a -> 'b) t -> 'a t -> 'b t val (<$>) : ('a -> 'b) -> 'a t -> 'b t val map2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t +val iter : ('a -> unit) -> 'a t -> unit +(** Iterate on 0 or 1 elements *) + +val fold : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a +(** Fold on 0 or 1 elements *) + (** {2 Conversion and IO} *) val to_list : 'a t -> 'a list +val of_list : 'a list -> 'a t +(** Head of list, or [None] *) + type 'a sequence = ('a -> unit) -> unit type 'a gen = unit -> 'a option type 'a printer = Buffer.t -> 'a -> unit