add CCList.fold_flat_map

This commit is contained in:
Simon Cruanes 2015-10-14 16:33:37 +02:00
parent b3cbb518b4
commit dd833cc667
3 changed files with 27 additions and 0 deletions

View file

@ -171,6 +171,27 @@ let fold_map f acc l =
fold_map (fun acc x -> x::acc, x) [] l = (List.rev l, l)) fold_map (fun acc x -> x::acc, x) [] l = (List.rev l, l))
*) *)
let fold_flat_map f acc l =
let rec aux f acc map_acc l = match l with
| [] -> acc, List.rev map_acc
| x :: l' ->
let acc, y = f acc x in
aux f acc (List.rev_append y map_acc) l'
in
aux f acc [] l
(*$=
(6, ["1"; "a1"; "2"; "a2"; "3"; "a3"]) \
(let pf = Printf.sprintf in \
fold_flat_map (fun acc x->acc+x, [pf "%d" x; pf "a%d" x]) 0 [1;2;3])
*)
(*$Q
Q.(list int) (fun l -> \
fold_flat_map (fun acc x -> x::acc, [x;x+10]) [] l = \
(List.rev l, flat_map (fun x->[x;x+10]) l) )
*)
let init len f = let init len f =
let rec init_rec acc i f = let rec init_rec acc i f =
if i=0 then f i :: acc if i=0 then f i :: acc

View file

@ -71,6 +71,11 @@ val fold_map : ('acc -> 'a -> 'acc * 'b) -> 'acc -> 'a list -> 'acc * 'b list
list to another list. list to another list.
@since NEXT_RELEASE *) @since NEXT_RELEASE *)
val fold_flat_map : ('acc -> 'a -> 'acc * 'b list) -> 'acc -> 'a list -> 'acc * 'b list
(** [fold_map f acc l] is a [fold_left]-like function, but it also maps the
list to a list of list that is then [flatten]'d..
@since NEXT_RELEASE *)
val init : int -> (int -> 'a) -> 'a t val init : int -> (int -> 'a) -> 'a t
(** Similar to {!Array.init} (** Similar to {!Array.init}
@since 0.6 *) @since 0.6 *)

View file

@ -149,6 +149,7 @@ let to_file filename format =
module type MONAD_IO = sig module type MONAD_IO = sig
type 'a t (** the IO monad *) type 'a t (** the IO monad *)
type output (** Output channels *) type output (** Output channels *)
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t val (>>=) : 'a t -> ('a -> 'b t) -> 'b t