s LearnSqueak.com

SMALLTALK LAB

Roman numerals: format numbers with ordered greedy tokens

Build a checked Roman numeral formatter in Squeak, trace its greedy choices, and compare every supported number with an independent place-value model.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use a disposable Squeak 6.1 image and open a Workspace. Each checkpoint is independent: paste one complete expression, select all of it and choose Print it. Do not paste its expected answer into the selection. Know Arrays, blocks and whileTrue: first; the collections and blocks lessons are useful preparation. No packages or network calls are required. This lesson implements a formatter for modern uppercase canonical numerals 1..3999; it does not implement a Roman numeral parser.

These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.

01 - Pair a value with its written token

Our formatter will choose from an ordered table. Each inner Array holds an integer value and a String. Here we read both parts of one pair. The word format means turning a number into text; we are not reading Roman text back into a number.

Independent Workspace expression - select all, then Print it
| pair |
pair := #(10 'X').
{pair first. pair second}

Expected: #(10 'X')

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Pair a value with its written token
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change the pair to #(5 'V'). Both the value and the text should change together.

Download this checkpoint

02 - Spend a remainder and append text

Take 23 and repeatedly use the token X, worth ten. Each use reduces the remaining amount by ten and appends one X. A WriteStream collects pieces without repeatedly copying the whole accumulated String. This is only a partial formatter: the remaining three units are deliberately not handled yet.

Independent Workspace expression - select all, then Print it
| left stream |
left := 23. stream := WriteStream on: String new.
[left >= 10] whileTrue: [
 stream nextPutAll: 'X'.
 left := left - 10].
{stream contents. left}

Expected: #('XX' 3)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Spend a remainder and append text
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: At every iteration, the value of written tokens plus left is still 23. Why does the loop terminate?

Download this checkpoint

03 - Give subtractive pairs their own tokens

In this modern canonical convention, four is IV and nine is IX. We treat each as one table entry, not as an instruction to subtract a character from the String. Descending order is important: choose nine before five, and four before one. Otherwise the formatter would emit a different spelling such as VIIII.

Independent Workspace expression - select all, then Print it
| tokens left stream |
tokens := #((10 'X') (9 'IX') (5 'V') (4 'IV') (1 'I')).
left := 14. stream := WriteStream on: String new.
tokens do: [:pair |
 [left >= pair first] whileTrue: [
  stream nextPutAll: pair second.
  left := left - pair first]].
{stream contents. left}

Expected: #('XIV' 0)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Give subtractive pairs their own tokens
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change 14 to 19. Expect XIX, not XVIIII. Try 4 and 9 as well.

Download this checkpoint

04 - Complete the table and state the contract

Add the hundreds and thousands, including XL, XC, CD and CM. The format block accepts only Integers from 1 through 3999. It signals an Error for zero, negatives, larger numbers and non-integers. This is a chosen display convention, not a claim that historical Roman writing had one universal spelling or no ways to represent larger quantities.

Independent Workspace expression - select all, then Print it
| tokens format |
tokens := #((1000 'M') (900 'CM') (500 'D') (400 'CD')
 (100 'C') (90 'XC') (50 'L') (40 'XL')
 (10 'X') (9 'IX') (5 'V') (4 'IV') (1 'I')).
format := [:number |
 | left stream |
 (number isInteger and: [number between: 1 and: 3999])
  ifFalse: [Error signal: 'Use an Integer from 1 to 3999'].
 left := number. stream := WriteStream on: String new.
 tokens do: [:pair |
  [left >= pair first] whileTrue: [
   stream nextPutAll: pair second.
   left := left - pair first]].
 stream contents].
format value: 1984

Expected: 'MCMLXXXIV'

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Complete the table and state the contract
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The decreasing table is part of the algorithm. Keep each value paired with its token, and keep the final value 1 so a valid remainder always reaches zero.

Download this checkpoint

05 - Format a collection without changing the inputs

The reusable block allocates its own remainder and output stream each time. collect: applies it to each input and returns a new collection of Strings. The original numbers are unchanged, and one call does not leave text behind for the next call.

Independent Workspace expression - select all, then Print it
| tokens format |
tokens := #((1000 'M') (900 'CM') (500 'D') (400 'CD')
 (100 'C') (90 'XC') (50 'L') (40 'XL')
 (10 'X') (9 'IX') (5 'V') (4 'IV') (1 'I')).
format := [:number |
 | left stream |
 (number isInteger and: [number between: 1 and: 3999])
  ifFalse: [Error signal: 'Use an Integer from 1 to 3999'].
 left := number. stream := WriteStream on: String new.
 tokens do: [:pair |
  [left >= pair first] whileTrue: [
   stream nextPutAll: pair second.
   left := left - pair first]].
 stream contents].
#(1 4 9 40 90 400 900 2026 3999)
 collect: [:number | format value: number]

Expected: #('I' 'IV' 'IX' 'XL' 'XC' 'CD' 'CM' 'MMXXVI' 'MMMCMXCIX')

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Format a collection without changing the inputs
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try adding 58 to the input Array. Expect LVIII at the matching output position.

Download this checkpoint

06 - Trace the decisions for one number

This trace records the token just written, the new remainder and the complete output so far. For 944 the chosen tokens are CM, XL and IV. The other table entries are checked but not emitted. Keep this distinction clear when animating: skipped entries are not zero-value tokens in the result.

Independent Workspace expression - select all, then Print it
| tokens left stream trace |
tokens := #((1000 'M') (900 'CM') (500 'D') (400 'CD')
 (100 'C') (90 'XC') (50 'L') (40 'XL')
 (10 'X') (9 'IX') (5 'V') (4 'IV') (1 'I')).
left := 944. stream := WriteStream on: String new.
trace := OrderedCollection new.
tokens do: [:pair |
 [left >= pair first] whileTrue: [
  stream nextPutAll: pair second.
  left := left - pair first.
  trace add: {pair second. left. stream contents copy}]].
trace asArray

Expected: #(('CM' 44 'CM') ('XL' 4 'CMXL') ('IV' 0 'CMXLIV'))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Trace the decisions for one number
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: For each trace row, recover the value of the written prefix from the tokens and add its remainder. The total must remain 944.

Download this checkpoint

07 - Reject invalid requests before writing

Use an Error handler around deliberate invalid calls so the Workspace lesson keeps running. A failed guard runs before the stream is created. The final valid call demonstrates that rejected requests do not poison later calls. A production UI should explain this error to the user rather than silently coercing 4.5 into an integer.

Independent Workspace expression - select all, then Print it
| tokens format rejected |
tokens := #((1000 'M') (900 'CM') (500 'D') (400 'CD')
 (100 'C') (90 'XC') (50 'L') (40 'XL')
 (10 'X') (9 'IX') (5 'V') (4 'IV') (1 'I')).
format := [:number |
 | left stream |
 (number isInteger and: [number between: 1 and: 3999])
  ifFalse: [Error signal: 'Use an Integer from 1 to 3999'].
 left := number. stream := WriteStream on: String new.
 tokens do: [:pair |
  [left >= pair first] whileTrue: [
   stream nextPutAll: pair second.
   left := left - pair first]].
 stream contents].
rejected := #(0 -1 4000 4.5) collect: [:bad |
 [format value: bad. false]
  on: Error do: [:error |
   error messageText = 'Use an Integer from 1 to 3999']].
{rejected. format value: 4}

Expected: #((true true true true) 'IV')

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Reject invalid requests before writing
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: 4.0 is a Float, so this contract rejects it even though its numerical value equals four. Convert deliberately before calling if your application needs that policy.

Download this checkpoint

08 - Compare every supported value with another construction

A test that repeats the same greedy loop would repeat its mistakes. Instead, build expected text from four independent place-value lookup tables: thousands, hundreds, tens and ones. Compare all 3999 supported numbers, then check rejected boundaries and types. Any mismatch signals an Error with the failing value; true means this entire expression completed successfully. This is a direct assertion script, not a SUnit test class.

Independent Workspace expression - select all, then Print it
| tokens format thousands hundreds tens ones expected rejected |
tokens := #((1000 'M') (900 'CM') (500 'D') (400 'CD')
 (100 'C') (90 'XC') (50 'L') (40 'XL')
 (10 'X') (9 'IX') (5 'V') (4 'IV') (1 'I')).
format := [:number |
 | left stream |
 (number isInteger and: [number between: 1 and: 3999])
  ifFalse: [Error signal: 'Use an Integer from 1 to 3999'].
 left := number. stream := WriteStream on: String new.
 tokens do: [:pair |
  [left >= pair first] whileTrue: [
   stream nextPutAll: pair second.
   left := left - pair first]].
 stream contents].
thousands := #('' 'M' 'MM' 'MMM').
hundreds := #('' 'C' 'CC' 'CCC' 'CD' 'D' 'DC' 'DCC' 'DCCC' 'CM').
tens := #('' 'X' 'XX' 'XXX' 'XL' 'L' 'LX' 'LXX' 'LXXX' 'XC').
ones := #('' 'I' 'II' 'III' 'IV' 'V' 'VI' 'VII' 'VIII' 'IX').
1 to: 3999 do: [:number |
 expected := (thousands at: (number // 1000) + 1),
  (hundreds at: ((number // 100) \\ 10) + 1),
  (tens at: ((number // 10) \\ 10) + 1),
  (ones at: (number \\ 10) + 1).
 (format value: number) = expected
  ifFalse: [Error signal: 'Mismatch at ', number printString]].
#(0 -1 4000 4.5 4.0 'IV' nil) do: [:bad |
 rejected := [format value: bad. false]
  on: Error do: [:error |
   error messageText = 'Use an Integer from 1 to 3999'].
 rejected ifFalse: [Error signal: 'Invalid input accepted']].
true

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Compare every supported value with another construction
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Temporarily swap IX to VIIII in the greedy table. The independent place-value expectation should catch the change. Restore IX afterward.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Roman numerals: format numbers with ordered greedy tokens native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.

Reason about correctness and limits

The table order is semantic, not decoration. IX must precede V and I; CM must precede D and C. Altering values or order invalidates the correctness argument.

The loop invariant is original value = emitted token values + remainder. Each emitted token is positive and no larger than the remainder, so remainder stays nonnegative and strictly decreases on an emission. The final I handles every remaining unit.

Greedy choice is not a universal optimization method. With denominations 4, 3 and 1, greedily making 6 uses 4+1+1, while 3+3 uses fewer tokens. Here we exploit this particular numeral convention and verify its bounded domain; we do not claim all greedy algorithms are optimal.

This code formats numbers; it does not validate input text such as IIV or IC. Parsing Roman text needs a separate grammar or a parse-and-canonicalize policy.

The bound is intentional. Clock faces may use IIII, and historical notation varies. Do not call other conventions invalid merely because this formatter chooses IV.

For this fixed range, the table has 13 entries and output length is bounded. More generally the loop does one pass over the table plus one iteration per emitted token; writing the output still costs proportional to its text length.

Three practice challenges

Label a small set of chapters

Format chapter numbers 1 through 12 without modifying the formatter.

Show solution

Use (1 to: 12) collect: [:chapter | format value: chapter] after the complete tokens and format definitions. The last three labels are X, XI and XII.

Return a trace as well as text

Extend the block with a local OrderedCollection holding each emitted token and remaining amount. Keep this state local to one call.

Show solution

Create trace beside stream. After each subtraction, add {pair second. left}. Return {stream contents. trace asArray}. For 944 the return begins with 'CMXLIV' and has the three trace rows shown in checkpoint 6. A separate API avoids changing callers that expect only a String.

Prove a decimal boundary

Write assertions for 39, 40, 49, 50, 89, 90 and 99. Why are these useful even with exhaustive tests?

Show solution

Expected results are XXXIX, XL, XLIX, L, LXXXIX, XC and XCIX. Compare each pair with format value:. Named boundary cases document the subtractive transitions and give more helpful failures than an unexplained large test count.

Continue learning

Collections | Blocks | Testing | First Association

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Windows.