From ee4ce9c9ba5b78c6d7702ec8f774aec5f5f8b9d0 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Tue, 29 Jan 2013 11:13:46 +0100 Subject: [PATCH] generic sequence pretty-printing function --- sequence.ml | 13 +++++++++++++ sequence.mli | 7 +++++++ tests.ml | 7 ++----- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/sequence.ml b/sequence.ml index 1ad632f..eb7e341 100644 --- a/sequence.ml +++ b/sequence.ml @@ -201,3 +201,16 @@ module Set = let module S = (val m : Set.S with type elt = s and type t = t) in fold (fun set x -> S.add x set) S.empty seq end + +(** {2 Pretty printing of sequences} *) + +(** Pretty print a sequence of ['a], using the given pretty printer + to print each elements. An optional separator string can be provided. *) +let pp_seq ?(sep=", ") pp_elt formatter seq = + let first = ref true in + iter + (fun x -> + (if !first then first := false else Format.pp_print_string formatter sep); + pp_elt formatter x; + Format.pp_print_cut formatter ()) + seq diff --git a/sequence.mli b/sequence.mli index e8396bc..9907c01 100644 --- a/sequence.mli +++ b/sequence.mli @@ -152,3 +152,10 @@ module Set : val to_seq : (module Set.S with type elt = 'a and type t = 'b) -> 'b -> 'a t val of_seq : (module Set.S with type elt = 'a and type t = 'b) -> 'a t -> 'b end + +(** {2 Pretty printing of sequences} *) + +val pp_seq : ?sep:string -> (Format.formatter -> 'a -> unit) -> + Format.formatter -> 'a t -> unit + (** Pretty print a sequence of ['a], using the given pretty printer + to print each elements. An optional separator string can be provided. *) diff --git a/tests.ml b/tests.ml index bace213..a6aa7a2 100644 --- a/tests.ml +++ b/tests.ml @@ -2,11 +2,8 @@ (** {2 Test sequences} *) (** print a list of items using the printing function *) -let rec pp_list ?(sep=", ") pp_item formatter = function - | x::y::xs -> Format.fprintf formatter "%a%s@,%a" - pp_item x sep (pp_list ~sep:sep pp_item) (y::xs) - | x::[] -> pp_item formatter x - | [] -> () +let pp_list ?(sep=", ") pp_item formatter l = + Sequence.pp_seq ~sep pp_item formatter (Sequence.List.to_seq l) (** Set of integers *) module ISet = Set.Make(struct type t = int let compare = compare end)