TExcelTAD
Home › OCaml › OCaml Buffer and Printf

OCaml Buffer and Printf

Strings are immutable, so building a long string with ^ in a loop copies the text again and again. For text assembled piece by piece, use a Buffer. For formatting values, use the Printf family. This lesson covers both, plus a short look at Format.

Printf format strings

Printf.printf prints, Printf.sprintf returns a string, Printf.eprintf writes to standard error, and Printf.bprintf appends to a buffer. They all use the same conversion specifications:

Spec Type Example output
%d / %i int 42
%5d / %-5d / %05d int 42 / 42 / 00042
%x / %X / %o int 2a / 2A / 52
%f / %.2f / %e / %g float 3.141593 / 3.14 / 3.141593e+00 / 3.14159
%s / %S string hi / "hi" (OCaml syntax)
%c / %C char a / 'a'
%b bool true
%a custom printer see below
%% a literal %
ocaml · try it yourself
let () =
  Printf.printf "[%d] [%5d] [%-5d] [%05d]\n" 42 42 42 42;
  Printf.printf "[%x] [%X] [%o] [%#x]\n" 255 255 8 255;
  Printf.printf "[%f] [%.3f] [%10.2f] [%e]\n" Float.pi Float.pi Float.pi 12345.678;
  Printf.printf "[%s] [%S] [%10s] [%-10s]\n" "hi" "hi" "right" "left";
  Printf.printf "[%c] [%C] [%b] [100%%]\n" 'z' 'z' false
[42] [   42] [42   ] [00042]
[ff] [FF] [10] [0xff]
[3.141593] [3.142] [      3.14] [1.234568e+04]
[hi] ["hi"] [     right] [left      ]
[z] ['z'] [false] [100%]

The format string is checked at compile time: the number and types of the arguments must match the specs.

ocaml · try it yourself
let () = Printf.printf "%d items\n" "three"
File "<source>", line 1, characters 36-43:
1 | let () = Printf.printf "%d items\n" "three"
                                        ^^^^^^^
Error: This constant has type string but an expression was expected of type
         int

Custom printers with %a

%a takes two arguments: a printing function and the value. The function receives the output channel (or buffer) first. This lets you print your own types inside a format:

ocaml · try it yourself
type point = { x : int; y : int }

let pp_point out p = Printf.fprintf out "(%d, %d)" p.x p.y

let () =
  let start = { x = 0; y = 0 } and finish = { x = 3; y = -2 } in
  Printf.printf "moved from %a to %a\n" pp_point start pp_point finish
moved from (0, 0) to (3, -2)

Buffer

A Buffer.t is a growable text buffer. Appending is cheap, and Buffer.contents produces the final string once:

ocaml · try it yourself
let render_table rows =
  let buf = Buffer.create 256 in
  Buffer.add_string buf "+--------+-------+\n";
  List.iter
    (fun (name, qty) -> Printf.bprintf buf "| %-6s | %5d |\n" name qty)
    rows;
  Buffer.add_string buf "+--------+-------+";
  Buffer.contents buf

let () =
  print_endline (render_table [ ("bolts", 120); ("nuts", 85); ("gears", 7) ])
+--------+-------+
| bolts  |   120 |
| nuts   |    85 |
| gears  |     7 |
+--------+-------+
Function Meaning
Buffer.create n new buffer (n is just an initial size hint)
Buffer.add_string b s, add_char b c append
Printf.bprintf b fmt ... append formatted text
Buffer.contents b the text so far, as a string
Buffer.length b, Buffer.clear b size, reset

Why not ^ in a loop?

Each ^ creates a new string and copies both sides. In a loop that is O(n²) work; a buffer is O(n):

ocaml · try it yourself
let join_with_buffer n =
  let b = Buffer.create 16 in
  for i = 1 to n do
    if i > 1 then Buffer.add_char b ',';
    Buffer.add_string b (string_of_int i)
  done;
  Buffer.contents b

let () =
  let s = join_with_buffer 10_000 in
  Printf.printf "length %d, ends with %s\n" (String.length s) (String.sub s (String.length s - 11) 11)
length 48893, ends with ,9999,10000

For joining a list, String.concat is already efficient.

Format: pretty printing

The Format module is a more powerful sibling of Printf, with automatic line breaking and indentation boxes. Its %a printers take a Format.formatter, and it is what most libraries use for their pp functions:

ocaml · try it yourself
let pp_list pp_item fmt items =
  Format.fprintf fmt "[@[<hov>%a@]]"
    (Format.pp_print_list ~pp_sep:(fun fmt () -> Format.fprintf fmt ";@ ") pp_item)
    items

let () =
  Format.printf "%a@." (pp_list Format.pp_print_int) (List.init 30 (fun i -> i * i))
[0; 1; 4; 9; 16; 25; 36; 49; 64; 81; 100; 121; 144; 169; 196; 225; 256; 289;
 324; 361; 400; 441; 484; 529; 576; 625; 676; 729; 784; 841]

@[<hov> opens a box, @ is a "break hint" (a space or a newline), @] closes the box and @. ends with a newline and flushes. The line was broken at the default margin of 80 columns.

Note: Format and Printf keep separate output buffers. Mixing Printf.printf and Format.printf in one program can print in a surprising order; pick one per program or flush between them.

Test yourself

What does Printf.sprintf "%05.1f" 3.14159 produce?

  1. "3.1"
  2. "003.1"
  3. "3.14159"
  4. "00003"

How many arguments does %a consume?

  1. One
  2. Two: a printer function and the value
  3. None
  4. Three

Why prefer Buffer over repeated ^ when building a large string?

  1. ^ is not allowed in loops
  2. Each ^ copies both strings, making the loop quadratic
  3. Buffers are immutable
  4. Buffers print automatically