From dd833cc667c5a51b4da647be412849a4607cffd0 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Wed, 14 Oct 2015 16:33:37 +0200 Subject: [PATCH] add `CCList.fold_flat_map` --- src/core/CCList.ml | 21 +++++++++++++++++++++ src/core/CCList.mli | 5 +++++ src/core/CCPrint.ml | 1 + 3 files changed, 27 insertions(+) diff --git a/src/core/CCList.ml b/src/core/CCList.ml index 3b9dbecc..4be891a6 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -171,6 +171,27 @@ let fold_map f acc 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 rec init_rec acc i f = if i=0 then f i :: acc diff --git a/src/core/CCList.mli b/src/core/CCList.mli index 2827b19f..06144586 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -71,6 +71,11 @@ val fold_map : ('acc -> 'a -> 'acc * 'b) -> 'acc -> 'a list -> 'acc * 'b list list to another list. @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 (** Similar to {!Array.init} @since 0.6 *) diff --git a/src/core/CCPrint.ml b/src/core/CCPrint.ml index e93b3339..9afcf7f9 100644 --- a/src/core/CCPrint.ml +++ b/src/core/CCPrint.ml @@ -149,6 +149,7 @@ let to_file filename format = module type MONAD_IO = sig type 'a t (** the IO monad *) + type output (** Output channels *) val (>>=) : 'a t -> ('a -> 'b t) -> 'b t