From 5e6ade9f6888b9101e5dd1bf4aa25d3f2ecc8b71 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Sat, 3 Oct 2015 15:51:02 +0200 Subject: [PATCH] add `CCList.fold_map` --- src/core/CCList.ml | 19 +++++++++++++++++++ src/core/CCList.mli | 5 +++++ 2 files changed, 24 insertions(+) diff --git a/src/core/CCList.ml b/src/core/CCList.ml index 2c6daaae..3b9dbecc 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -152,6 +152,25 @@ let rec fold_while f acc = function fold_while (fun acc b -> if b then acc+1, `Continue else acc, `Stop) 0 [true;true;false;true] = 2 *) +let fold_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 (y :: map_acc) l' + in + aux f acc [] l + +(*$= + (6, ["1"; "2"; "3"]) \ + (fold_map (fun acc x->acc+x, string_of_int x) 0 [1;2;3]) +*) + +(*$Q + Q.(list int) (fun l -> \ + fold_map (fun acc x -> x::acc, x) [] l = (List.rev l, 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 02d8c1ce..2827b19f 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -66,6 +66,11 @@ val fold_while : ('a -> 'b -> 'a * [`Stop | `Continue]) -> 'a -> 'b t -> 'a indicated by the accumulator @since 0.8 *) +val fold_map : ('acc -> 'a -> 'acc * 'b) -> 'acc -> 'a list -> 'acc * 'b list +(** [fold_map f acc l] is a [fold_left]-like function, but it also maps the + list to another list. + @since NEXT_RELEASE *) + val init : int -> (int -> 'a) -> 'a t (** Similar to {!Array.init} @since 0.6 *)