Skip to content
Groups & Decisions
step 1/5

Reading — step 1 of 5

Read

~1 min readWadler's Algebra

Groups & Decisions

GROUP(d) means: try to render d on one line. If it fits within remaining width, render flat. Else: render with line breaks.

This is the critical decision in a pretty printer.

Algorithm:

python

Hughes' (predecessor) algorithm could be exponential. Wadler's improvement: linear.

Wadler's idea: pretty(width, ribbon, doc) returns a layout. Layout chooses for each GROUP.

Pseudocode:

python

Each GROUP makes one decision. Once decided, contained children inherit the parent's decision.

Bestcase O(n). Worstcase still O(n) for greedy variant. Optimal layout minimizes height + adheres to width.

Real prettier and Wadler descendents use this exact pattern.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…