diff --git a/src/core/CCResult.ml b/src/core/CCResult.ml index 05a23f23..9fd490b2 100644 --- a/src/core/CCResult.ml +++ b/src/core/CCResult.ml @@ -1,4 +1,3 @@ - (* This file is free software, part of containers. See file "license" for more details. *) (** {1 Error Monad} *) @@ -218,6 +217,19 @@ let map_l f l = | Ok y -> map (y::acc) l' in map [] l +let flatten_l l = + let rec loop acc l = match l with + | [] -> Ok (List.rev acc) + | Ok x::l' -> loop (x::acc) l' + | Error e::_ -> Error e + in loop [] l + +(*$= + (Ok []) (flatten_l []) + (Ok [1;2;3]) (flatten_l [Ok 1; Ok 2; Ok 3]) + (Error "ohno") (flatten_l [Ok 1; Error "ohno"; Ok 2; Ok 3; Error "wut"]) +*) + exception LocalExit let fold_seq f acc seq = diff --git a/src/core/CCResult.mli b/src/core/CCResult.mli index a8faf8a5..ec8c7a4c 100644 --- a/src/core/CCResult.mli +++ b/src/core/CCResult.mli @@ -1,4 +1,3 @@ - (* This file is free software, part of containers. See file "license" for more details. *) (** {1 Error Monad} @@ -187,6 +186,12 @@ end (** {2 Collections} *) +val flatten_l : ('a, 'err) t list -> ('a list, 'err) t +(** Same as [map_l id]: returns [Ok [x1;…;xn]] if [l=[Ok x1; …; Ok xn]], + or the first error otherwise. + @since NEXT_RELEASE +*) + val map_l : ('a -> ('b, 'err) t) -> 'a list -> ('b list, 'err) t (** [map_l f [a1; ...; an]] applies the function [f] to [a1, ..., an] , and, in case of success for every element, returns the list of [Ok]-value.