Reading — step 1 of 5
Learn
OCaml's Printf is type-checked at compile time. The Format module goes further — pretty-printing with boxes, indentation, and line breaks.
open Format
let () =
printf "@[<v 2>Result:@,%d@,%s@]@." 42 "hello"
Format directives in @:
@[<v 2>— open vertical box, indent 2@[<h>— horizontal box (no breaks)@[<hv 2>— horizontal-or-vertical (try horizontal, break to vertical if too wide)@,— break point (line break in vertical, space in horizontal)@— break or space@]— close box@.— newline + flush
Pretty printing custom types:
type tree = Leaf | Node of int * tree * tree
let rec pp_tree fmt = function
| Leaf -> Format.pp_print_string fmt "leaf"
| Node (v, l, r) ->
Format.fprintf fmt "@[<v 2>node %d@,%a@,%a@]" v pp_tree l pp_tree r
let () =
let t = Node (1, Node (2, Leaf, Leaf), Node (3, Leaf, Leaf)) in
Format.printf "%a@." pp_tree t
Outputs:
node 1
node 2
leaf
leaf
node 3
leaf
leaf
%a is the directive for "call this printer."
Buffer module for string building:
let buf = Buffer.create 256
Buffer.add_string buf "Hello, ";
Buffer.add_string buf "World!";
Buffer.add_char buf '\n';
print_string (Buffer.contents buf)
Far more efficient than repeated ^ concatenation for large strings — ^ is O(n+m) every call.
Printf.sprintf for one-shot formatting:
let greeting = Printf.sprintf "Hello, %s, age %d" name age
Type-safe format strings — %d requires int, etc. If types don't match, compile error:
Printf.printf "%d" "hello" (* compile error — %d wants int *)
Most OCaml standard library reaches for Format (e.g., Format.printf from Pervasives). Real packages provide custom pp_* functions for their types.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…