feat(CCString): add CCString.uniq

CCString.uniq remove consecutive duplicate characters
This commit is contained in:
Fardale 2021-04-08 23:08:30 +02:00
parent e75d93bb9d
commit 375ae27622
3 changed files with 26 additions and 0 deletions

View file

@ -1000,6 +1000,24 @@ let filter f s =
Q.printable_string (fun s -> filter (fun _ -> true) s = 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 flat_map ?sep f s =
let buf = Buffer.create (String.length s) in let buf = Buffer.create (String.length s) in
iteri iteri

View file

@ -249,6 +249,10 @@ val filter : (char -> bool) -> string -> string
(** [filter f s] discards characters of [s] not satisfying [f]. (** [filter f s] discards characters of [s] not satisfying [f].
@since 0.17 *) @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 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. (** [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. @param sep optional separator between each generated string.

View file

@ -254,6 +254,10 @@ val filter : f:(char -> bool) -> string -> string
(** [filter ~f s] discards characters of [s] not satisfying [f]. (** [filter ~f s] discards characters of [s] not satisfying [f].
@since 0.17 *) @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 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. (** [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. @param sep optional separator between each generated string.