Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CCBool: Add functions if_then and if_then_else #442

Merged
merged 1 commit into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/core/CCBool.ml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
8 changes: 8 additions & 0 deletions src/core/CCBool.mli
Original file line number Diff line number Diff line change
Expand Up @@ -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 *)
Expand Down
6 changes: 5 additions & 1 deletion tests/core/t_bool.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading