CCBool: Add functions if_then and if_then_else

This commit is contained in:
Master Builder 2023-11-26 19:17:48 +00:00 committed by Simon Cruanes
parent fdb7c0f4b0
commit 77bfa34355
3 changed files with 25 additions and 3 deletions

View file

@ -1,12 +1,22 @@
(* This file is free software, part of containers. See file "license" for more details. *)
type t = bool
let equal (a : bool) b = Stdlib.( = ) a b
let compare (a : bool) b = Stdlib.compare a b
let if_then f x =
if x then
Some (f ())
else
None
let if_then_else f g x =
if x then
f ()
else
g ()
let to_int (x : bool) : int =
if x then
1

View file

@ -10,6 +10,14 @@ val compare : t -> t -> int
val equal : t -> t -> bool
(** [equal b1 b2] is [true] if [b1] and [b2] are the same. *)
val if_then : (unit -> 'a) -> t -> 'a option
(** [if_then f x] is [Some (f ())] if [x] is true and None otherwise.
@since NEXT_RELEASE *)
val if_then_else : (unit -> 'a) -> (unit -> 'a) -> t -> 'a
(** [if_then_else f g x] is [f ()] if [x] is true and [g ()] otherwise.
@since NEXT_RELEASE *)
val to_int : t -> int
(** [to_int true = 1], [to_int false = 0].
@since 2.7 *)

View file

@ -8,4 +8,8 @@ eq true (of_int 1);;
eq false (of_int 0);;
eq true (of_int 42);;
eq true (of_int max_int);;
eq true (of_int min_int)
eq true (of_int min_int);;
eq (Some "true") (if_then (Fun.const "true") true);;
eq None (if_then (Fun.const "true") false);;
eq "true" (if_then_else (Fun.const "true") (Fun.const "false") true);;
eq "false" (if_then_else (Fun.const "true") (Fun.const "false") false)