From d0b05fdb760a9c30473523e72f3360e1465c31be Mon Sep 17 00:00:00 2001 From: Kye Shi Date: Sat, 12 Dec 2020 17:53:13 -0800 Subject: [PATCH] CCFormat: add `append`, `append_l`, infix `++` for sequencing --- src/core/CCFormat.ml | 24 ++++++++++++++++++++++++ src/core/CCFormat.mli | 13 +++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/core/CCFormat.ml b/src/core/CCFormat.ml index 927c5131..12750784 100644 --- a/src/core/CCFormat.ml +++ b/src/core/CCFormat.ml @@ -107,6 +107,24 @@ let triple ?(sep=return ",@ ") ppa ppb ppc fmt (a, b, c) = let quad ?(sep=return ",@ ") ppa ppb ppc ppd fmt (a, b, c, d) = Format.fprintf fmt "%a%a%a%a%a%a%a" ppa a sep () ppb b sep () ppc c sep () ppd d +let append ppa ppb fmt () = + ppa fmt (); + ppb fmt () + +(*$= append & ~printer:(fun s -> CCFormat.sprintf "%S" s) + "foobar" (to_string_test (append (return "foo") (return "bar"))) + "bar" (to_string_test (append (return "") (return "bar"))) + "foo" (to_string_test (append (return "foo") (return ""))) +*) + +let append_l = List.fold_left append (return "") + +(*$= append_l & ~printer:(fun s -> CCFormat.sprintf "%S" s) + "" (to_string_test @@ append_l []) + "foobarbaz" (to_string_test @@ append_l (List.map return ["foo"; "bar"; "baz"])) + "3141" (to_string_test @@ append_l (List.map (const int) [3; 14; 1])) +*) + let within a b p out x = string out a; p out x; @@ -444,3 +462,9 @@ end "[(Ok \"a b c\");(Error \"nope\")]" \ (to_string Dump.(list (result string)) [Ok "a b c"; Error "nope"]) *) + +module Infix = struct + let (++) = append +end + +include Infix diff --git a/src/core/CCFormat.mli b/src/core/CCFormat.mli index 286e3118..c82cd2f9 100644 --- a/src/core/CCFormat.mli +++ b/src/core/CCFormat.mli @@ -95,6 +95,12 @@ val triple : ?sep:unit printer -> 'a printer -> 'b printer -> 'c printer -> ('a val quad : ?sep:unit printer -> 'a printer -> 'b printer -> 'c printer -> 'd printer -> ('a * 'b * 'c * 'd) printer +val append : unit printer -> unit printer -> unit printer +(** [append ppa ppb] first prints [ppa ()], then prints [ppb ()]. *) + +val append_l : unit printer list -> unit printer +(** [append_l pps] runs the printers in [pps] sequentially. *) + val within : string -> string -> 'a printer -> 'a printer (** [within a b p] wraps [p] inside the strings [a] and [b]. Convenient, for instances, for brackets, parenthesis, quotes, etc. @@ -349,3 +355,10 @@ module Dump : sig val to_string : 'a t -> 'a -> string (** Alias to {!CCFormat.to_string}. *) end + +module Infix : sig + val (++) : unit printer -> unit printer -> unit printer + (** Alias to {!append}. *) +end + +include module type of Infix