more functions for CCOpt

This commit is contained in:
Simon Cruanes 2014-06-03 17:03:25 +02:00
parent fd88f10216
commit 945325054f
2 changed files with 29 additions and 0 deletions

View file

@ -58,6 +58,10 @@ let (>>=) o f = match o with
| None -> None | None -> None
| Some x -> f x | 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 let (<*>) f x = match f, x with
| None, _ | None, _
| _, None -> None | _, None -> None
@ -70,10 +74,22 @@ let map2 f o1 o2 = match o1, o2 with
| _, None -> None | _, None -> None
| Some x, Some y -> Some (f x y) | 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 let to_list o = match o with
| None -> [] | None -> []
| Some x -> [x] | Some x -> [x]
let of_list = function
| x::_ -> Some x
| [] -> None
type 'a sequence = ('a -> unit) -> unit type 'a sequence = ('a -> unit) -> unit
type 'a gen = unit -> 'a option type 'a gen = unit -> 'a option
type 'a printer = Buffer.t -> 'a -> unit type 'a printer = Buffer.t -> 'a -> unit

View file

@ -29,6 +29,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
type 'a t = 'a option type 'a t = 'a option
val map : ('a -> 'b) -> 'a t -> 'b t val map : ('a -> 'b) -> 'a t -> 'b t
(** Transform the element inside, if any *)
val maybe : ('a -> 'b) -> 'b -> 'a t -> 'b 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] *) (** [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 val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
(** Monadic bind *) (** 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) t -> 'a t -> 'b t
val (<$>) : ('a -> 'b) -> 'a t -> 'b t val (<$>) : ('a -> 'b) -> 'a t -> 'b t
val map2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c 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} *) (** {2 Conversion and IO} *)
val to_list : 'a t -> 'a list 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 sequence = ('a -> unit) -> unit
type 'a gen = unit -> 'a option type 'a gen = unit -> 'a option
type 'a printer = Buffer.t -> 'a -> unit type 'a printer = Buffer.t -> 'a -> unit