From 4ad331fbe37d993b7368e57fb54b27631f38bb36 Mon Sep 17 00:00:00 2001 From: Fardale Date: Fri, 12 Mar 2021 18:13:03 +0100 Subject: [PATCH] feat(CCString): add CCString.foldi --- src/core/CCString.ml | 6 ++++++ src/core/CCString.mli | 5 +++++ src/core/CCStringLabels.mli | 5 +++++ 3 files changed, 16 insertions(+) diff --git a/src/core/CCString.ml b/src/core/CCString.ml index aa250b1b..8c276c2c 100644 --- a/src/core/CCString.ml +++ b/src/core/CCString.ml @@ -760,6 +760,12 @@ let fold f acc s = else fold_rec f (f acc s.[i]) s (i+1) in fold_rec f acc s 0 +let foldi f acc s = + let rec fold_rec f acc s i = + if i = String.length s then acc + else fold_rec f (f acc i s.[i]) s (i+1) + in fold_rec f acc s 0 + let pad ?(side=`Left) ?(c=' ') n s = let len_s = String.length s in if len_s >= n then s diff --git a/src/core/CCString.mli b/src/core/CCString.mli index fabe76ea..d27c0b13 100644 --- a/src/core/CCString.mli +++ b/src/core/CCString.mli @@ -34,6 +34,11 @@ val fold : ('a -> char -> 'a) -> 'a -> t -> 'a (** [fold f init s] folds on chars by increasing index. Computes [f(… (f (f init s.[0]) s.[1]) …) s.[n-1]]. @since 0.7 *) +val foldi : ('a -> int -> char -> 'a) -> 'a -> t -> 'a +(** [foldi f init s] is just like {!fold}, but it also passes in the index of each chars + as second argument to the folded function [f]. + @since NEXT_RELEASE *) + (** {2 Conversions} *) val to_gen : t -> char gen diff --git a/src/core/CCStringLabels.mli b/src/core/CCStringLabels.mli index 5dc09d09..4b7cf55b 100644 --- a/src/core/CCStringLabels.mli +++ b/src/core/CCStringLabels.mli @@ -34,6 +34,11 @@ val fold : f:('a -> char -> 'a) -> init:'a -> t -> 'a (** [fold ~f ~init s] folds on chars by increasing index. Computes [f(… (f (f init s.[0]) s.[1]) …) s.[n-1]]. @since 0.7 *) +val foldi : f:('a -> int -> char -> 'a) -> 'a -> t -> 'a +(** [foldi ~f init s] is just like {!fold}, but it also passes in the index of each chars + as second argument to the folded function [f]. + @since NEXT_RELEASE *) + (** {2 Conversions} *) val to_gen : t -> char gen