diff --git a/src/core/CCBool.ml b/src/core/CCBool.ml index 9166bd7bd..b7e97bb55 100644 --- a/src/core/CCBool.ml +++ b/src/core/CCBool.ml @@ -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 diff --git a/src/core/CCBool.mli b/src/core/CCBool.mli index 9fda5922d..d179f95d8 100644 --- a/src/core/CCBool.mli +++ b/src/core/CCBool.mli @@ -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 *) diff --git a/tests/core/t_bool.ml b/tests/core/t_bool.ml index 9d8e3b98a..37cc41233 100644 --- a/tests/core/t_bool.ml +++ b/tests/core/t_bool.ml @@ -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)