diff --git a/src/core/CCList.ml b/src/core/CCList.ml index d29cdc1d..d42c56b9 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -74,6 +74,8 @@ let is_empty = function | [] -> true | _::_ -> false +let mguard c = if c then [ () ] else [] + (* max depth for direct recursion *) let direct_depth_default_ = 1000 diff --git a/src/core/CCList.mli b/src/core/CCList.mli index 70424924..12cfb90c 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -322,6 +322,20 @@ val interleave : 'a list -> 'a list -> 'a list val pure : 'a -> 'a t (** [pure x] is [return x]. *) +val mguard : bool -> unit t +(** [mguard c] is [pure ()] if [c] is true, [[]] otherwise. + This is useful to define a list by comprehension, e.g.: + {[ + # let square_even xs = + let* x = xs in + let* () = mguard (x mod 2 = 0) in + return @@ x * x;; + val square_even : int list -> int list = + # square_even [1;2;4;3;5;2];; + - : int list = [4; 16; 4] + ]} + @since 3.1 *) + val (<*>) : ('a -> 'b) t -> 'a t -> 'b t (** [funs <*> l] is [product (fun f x -> f x) funs l]. *) diff --git a/src/core/CCListLabels.mli b/src/core/CCListLabels.mli index 69a21705..61734064 100644 --- a/src/core/CCListLabels.mli +++ b/src/core/CCListLabels.mli @@ -326,6 +326,20 @@ val interleave : 'a list -> 'a list -> 'a list val pure : 'a -> 'a t (** [pure x] is [return x]. *) +val mguard : bool -> unit t +(** [mguard c] is [pure ()] if [c] is true, [[]] otherwise. + This is useful to define a list by comprehension, e.g.: + {[ + # let square_even xs = + let* x = xs in + let* () = mguard (x mod 2 = 0) in + return @@ x * x;; + val square_even : int list -> int list = + # square_even [1;2;4;3;5;2];; + - : int list = [4; 16; 4] + ]} + @since 3.1 *) + val (<*>) : ('a -> 'b) t -> 'a t -> 'b t (** [funs <*> l] is [product (fun f x -> f x) funs l]. *)