s LearnSqueak.com

SMALLTALK LAB

Balanced brackets: a stack that remembers nesting

Build a three-bracket validator, distinguish unmatched and crossed pairs, and watch the stack grow and shrink in genuine Squeak captures.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Know characters, collections and conditional blocks. This lesson validates bracket structure in plain text. It is deliberately not a Smalltalk parser: brackets inside quoted text still count.

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 - Recognize an opener

A String is a sequence of characters. includes: asks whether a character is among the three opening delimiters. A dollar sign creates a Character literal in Smalltalk.

Independent Workspace expression - select all, then Print it
{('([{' includes: $[). ('([{' includes: $x)}

Expected: {true. false.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Recognize an opener
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try $( and ${; both should be recognized.

Download this checkpoint

02 - Store the expected matching opener

Map each closing character to its required opening character. The final brace in the last association closes a dynamic Array; the brace after the dollar sign is the Character itself.

Independent Workspace expression - select all, then Print it
| pairs |
pairs := Dictionary newFrom: {$) -> $(. $] -> $[. $} -> ${}.
pairs at: $]

Expected: $[

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Store the expected matching opener
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Query $) to get $(.

Download this checkpoint

03 - Use the end of a collection as a stack

The most recent opener must be closed first. add: pushes at the end; removeLast pops that same end. This last-in-first-out rule is what a mere counter cannot remember.

Independent Workspace expression - select all, then Print it
| stack last |
stack := OrderedCollection new.
stack add: $(; add: $[.
last := stack removeLast.
{last. stack asArray}

Expected: {$[. {$(}}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Use the end of a collection as a stack
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Push ${ too: it becomes the first character removed.

Download this checkpoint

04 - Validate one kind before generalizing

A counter is enough for parentheses alone. Never allow depth below zero, and require zero at the end. This checkpoint demonstrates the simpler model that will fail to distinguish crossed bracket types.

Independent Workspace expression - select all, then Print it
| depth valid |
depth := 0. valid := true.
'(())' do: [:c |
 c = $( ifTrue: [depth := depth+1].
 c = $) ifTrue: [depth := depth-1].
 depth < 0 ifTrue: [valid := false]].
valid and: [depth = 0]

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Validate one kind before generalizing
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Use )( : the final depth is zero, but valid is false.

Download this checkpoint

05 - Validate all three kinds

Push openers. On a closer, reject an empty stack before popping; otherwise compare the popped opener to the Dictionary entry. Once invalid, stop changing state. At the end, a leftover opener is also invalid.

Independent Workspace expression - select all, then Print it
| balanced |
balanced := [:text | | stack pairs valid |
 stack := OrderedCollection new.
 pairs := Dictionary newFrom: {$) -> $(. $] -> $[. $} -> ${}.
 valid := true.
 text do: [:c |
  valid ifTrue: [
   ('([{' includes: c) ifTrue: [stack add: c].
   (pairs includesKey: c) ifTrue: [
    stack isEmpty
     ifTrue: [valid := false]
     ifFalse: [valid := stack removeLast = (pairs at: c)]]]].
 valid and: [stack isEmpty]].
balanced value: 'a{b[c(d)e]f}g'

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Validate all three kinds
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Ordinary letters are ignored. Remove the last } to leave an unclosed opener.

Download this checkpoint

06 - Catch crossings as well as missing pairs

The input ([)] has equal numbers of openers and closers but crosses their nesting. The top of the stack is [ when ) arrives, so the mismatch must be rejected.

Independent Workspace expression - select all, then Print it
| balanced |
balanced := [:text | | stack pairs valid |
 stack := OrderedCollection new.
 pairs := Dictionary newFrom: {$) -> $(. $] -> $[. $} -> ${}.
 valid := true.
 text do: [:c |
  valid ifTrue: [
   ('([{' includes: c) ifTrue: [stack add: c].
   (pairs includesKey: c) ifTrue: [
    stack isEmpty
     ifTrue: [valid := false]
     ifFalse: [valid := stack removeLast = (pairs at: c)]]]].
 valid and: [stack isEmpty]].
#('([)]' ']' '((' '([])' '') collect: [:s | balanced value: s]

Expected: {false. false. false. true. true.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Catch crossings as well as missing pairs
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Empty text is balanced: there are no unclosed brackets.

Download this checkpoint

07 - Check a family of valid nests

Generate increasingly deep repeated parentheses and validate every result. This tests the empty case and deeper stack sizes without recursion or a hand-written list of expected strings.

Independent Workspace expression - select all, then Print it
| balanced |
balanced := [:text | | stack pairs valid |
 stack := OrderedCollection new.
 pairs := Dictionary newFrom: {$) -> $(. $] -> $[. $} -> ${}.
 valid := true.
 text do: [:c |
  valid ifTrue: [
   ('([{' includes: c) ifTrue: [stack add: c].
   (pairs includesKey: c) ifTrue: [
    stack isEmpty
     ifTrue: [valid := false]
     ifFalse: [valid := stack removeLast = (pairs at: c)]]]].
 valid and: [stack isEmpty]].
(0 to: 30) allSatisfy: [:n |
 balanced value: ((String new: n withAll: $(),
  (String new: n withAll: $)))]

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Check a family of valid nests
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Append one extra ] to every generated string; all should become false.

Download this checkpoint

08 - Expose the parser boundary

The validator sees every bracket, even between apostrophes. That is correct for its plain-text contract but not sufficient for source code. A language-aware checker would first tokenize strings and comments.

Independent Workspace expression - select all, then Print it
| balanced quoted |
balanced := [:text | | stack pairs valid |
 stack := OrderedCollection new.
 pairs := Dictionary newFrom: {$) -> $(. $] -> $[. $} -> ${}.
 valid := true.
 text do: [:c |
  valid ifTrue: [
   ('([{' includes: c) ifTrue: [stack add: c].
   (pairs includesKey: c) ifTrue: [
    stack isEmpty
     ifTrue: [valid := false]
     ifFalse: [valid := stack removeLast = (pairs at: c)]]]].
 valid and: [stack isEmpty]].
quoted := String with: $' with: $[ with: $'.
balanced value: quoted

Expected: false

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Expose the parser boundary
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Explain why a bracket in a Smalltalk string should not affect a full parser.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Balanced brackets: a stack that remembers nesting 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

With n characters, each character performs a fixed amount of work and every bracket is pushed or popped at most once: O(n) time and O(d) stack space for maximum nesting depth d.

A stack underflow is a normal invalid-input condition, not a reason to call removeLast blindly. Check isEmpty before popping.

This block reports only true or false. For an editor, track positions alongside openers and return the first mismatch position and expected closer. Quotes, comments, escapes and language grammar require additional tokenization.

Three practice challenges

Challenge 1

Why can one depth counter accept ([)] incorrectly?

Show solution

It records how many brackets are open but forgets their types and order.

Challenge 2

How could you return the unmatched opener position?

Show solution

Push associations from character to position, increment a position counter while scanning, and keep those records on the stack.

Challenge 3

Does concatenating two balanced plain-text strings preserve balance?

Show solution

Yes. Each finishes with an empty stack, so the second begins with the same empty state as a separate validation.

Continue learning

Stacks Queues | First Character | Tiny Language

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