add Result.flatten_l to turn a list of results into a result of list

This commit is contained in:
Simon Cruanes 2019-10-16 12:22:55 -05:00
parent 0c23e3ba88
commit df9bbb8746
2 changed files with 19 additions and 2 deletions

View file

@ -1,4 +1,3 @@
(* This file is free software, part of containers. See file "license" for more details. *) (* This file is free software, part of containers. See file "license" for more details. *)
(** {1 Error Monad} *) (** {1 Error Monad} *)
@ -218,6 +217,19 @@ let map_l f l =
| Ok y -> map (y::acc) l' | Ok y -> map (y::acc) l'
in map [] 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 exception LocalExit
let fold_seq f acc seq = let fold_seq f acc seq =

View file

@ -1,4 +1,3 @@
(* This file is free software, part of containers. See file "license" for more details. *) (* This file is free software, part of containers. See file "license" for more details. *)
(** {1 Error Monad} (** {1 Error Monad}
@ -187,6 +186,12 @@ end
(** {2 Collections} *) (** {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 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 (** [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. success for every element, returns the list of [Ok]-value.