From 375ae27622bbec6d59a26ff58620da8fc74189d4 Mon Sep 17 00:00:00 2001 From: Fardale Date: Thu, 8 Apr 2021 23:08:30 +0200 Subject: [PATCH] feat(CCString): add CCString.uniq CCString.uniq remove consecutive duplicate characters --- src/core/CCString.ml | 18 ++++++++++++++++++ src/core/CCString.mli | 4 ++++ src/core/CCStringLabels.mli | 4 ++++ 3 files changed, 26 insertions(+) diff --git a/src/core/CCString.ml b/src/core/CCString.ml index add7afd4..a651349b 100644 --- a/src/core/CCString.ml +++ b/src/core/CCString.ml @@ -1000,6 +1000,24 @@ let filter f s = Q.printable_string (fun s -> filter (fun _ -> true) s = s) *) +let uniq eq s = + if String.length s = 0 then s + else begin + let buf = Buffer.create (String.length s) in + Buffer.add_char buf s.[0]; + let _ = fold + (fun previous_c c -> + if not (eq previous_c c) then Buffer.add_char buf c; + c + ) + s.[0] s in + Buffer.contents buf + end + +(*$= & ~printer:Q.Print.string + "abcde" (uniq CCShims_.Stdlib.(=) "abbccdeeeee") +*) + let flat_map ?sep f s = let buf = Buffer.create (String.length s) in iteri diff --git a/src/core/CCString.mli b/src/core/CCString.mli index d50a4f68..f6a76d77 100644 --- a/src/core/CCString.mli +++ b/src/core/CCString.mli @@ -249,6 +249,10 @@ val filter : (char -> bool) -> string -> string (** [filter f s] discards characters of [s] not satisfying [f]. @since 0.17 *) +val uniq : (char -> char -> bool) -> string -> string +(** [uniq eq s] remove consecutive duplicate characters in [s]. + @since NEXT_RELEASE *) + val flat_map : ?sep:string -> (char -> string) -> string -> string (** [flat_map ~sep f s] maps each chars of [s] to a string, then concatenates them all. @param sep optional separator between each generated string. diff --git a/src/core/CCStringLabels.mli b/src/core/CCStringLabels.mli index 757bd649..b050288c 100644 --- a/src/core/CCStringLabels.mli +++ b/src/core/CCStringLabels.mli @@ -254,6 +254,10 @@ val filter : f:(char -> bool) -> string -> string (** [filter ~f s] discards characters of [s] not satisfying [f]. @since 0.17 *) +val uniq : eq:(char -> char -> bool) -> string -> string +(** [uniq ~eq s] remove consecutive duplicate characters in [s]. + @since NEXT_RELEASE *) + val flat_map : ?sep:string -> f:(char -> string) -> string -> string (** [flat_map ?sep ~f s] maps each chars of [s] to a string, then concatenates them all. @param sep optional separator between each generated string.