Chuyển đến nội dung

Bài 38 · Projects and Practice

Practice: Smalltalk Exercises

Twelve graded Smalltalk exercises on messages, blocks, collections, classes, reflection and tests. Read the Smalltalk solutions, then check the ideas with runnable JavaScript stand-ins.

You learn a language by writing it. These twelve exercises revisit the whole track, from messages and blocks to metaclasses and tests. Each has a task, a hint and a solution. Because Smalltalk does not run on this site, solutions are shown read-only; try them in a Pharo or Squeak image, using the Playground to check each result. Where a quick runnable check helps, a JavaScript stand-in verifies the logic so you can compare answers.

Work in order. Try each exercise for at least ten minutes before reading the solution.

Warm-up: messages and blocks

1. Precedence. What does each expression return? 2 + 3 * 4, 2 + (3 * 4), 10 - 2 - 3, 2 raisedTo: 3 + 1.

Solution. Binary messages go left to right: 20, 14, 5, and 16 (the binary + runs before the keyword).

JS Check exercise 1

Press Run (or Ctrl + Enter) to see the console output here.

No output.

2. A block with arguments. Write a block average that takes two numbers and returns their average, then evaluate it with 4 and 10.

Solution (read-only):

SMALLTALK
| average |
average := [ :a :b | (a + b) / 2 ].
average value: 4 value: 10.    "7"

3. Count the vowels. Return how many vowels are in 'object oriented'.

SMALLTALK
('object oriented' select: [ :c | c isVowel ]) size.     "6"

Collections and control flow

4. FizzBuzz. Print numbers 1 to 15, but Fizz for multiples of 3, Buzz for 5 and FizzBuzz for both.

SMALLTALK
1 to: 15 do: [ :i |
    Transcript show: (
        (i \\ 15 = 0) ifTrue: [ 'FizzBuzz' ] ifFalse: [
        (i \\ 3 = 0) ifTrue: [ 'Fizz' ] ifFalse: [
        (i \\ 5 = 0) ifTrue: [ 'Buzz' ] ifFalse: [ i printString ] ] ]);
        cr ]
JS Check exercise 4

Press Run (or Ctrl + Enter) to see the console output here.

No output.

5. Word frequency. Given #('a' 'b' 'a' 'c' 'a' 'b'), build a dictionary of counts. Hint: Bag or Dictionary at:ifAbsent:.

SMALLTALK
| counts |
counts := Dictionary new.
#('a' 'b' 'a' 'c' 'a' 'b') do: [ :w |
    counts at: w put: (counts at: w ifAbsent: [ 0 ]) + 1 ].
counts.     "a->3, b->2, c->1"

6. Sorted by length. Sort #('pear' 'fig' 'banana' 'kiwi') by length, longest first.

SMALLTALK
#('pear' 'fig' 'banana' 'kiwi') asSortedCollection: [ :a :b | a size >= b size ].
JS Check exercises 5 and 6

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Classes and objects

7. A Stack class. Create Stack with push:, pop, top, isEmpty and size. pop on an empty stack should signal an error.

SMALLTALK
Object subclass: #Stack
    instanceVariableNames: 'items'
    package: 'Practice'.

Stack >> initialize
    super initialize.
    items := OrderedCollection new

Stack >> push: anObject
    items addLast: anObject.
    ^ anObject

Stack >> pop
    items ifEmpty: [ ^ self error: 'stack is empty' ].
    ^ items removeLast

Stack >> top
    ^ items last

Stack >> isEmpty
    ^ items isEmpty

Stack >> size
    ^ items size

8. Polymorphism. Create Shape with area as self subclassResponsibility, and Circle and Rectangle subclasses. Sum the areas of a list of shapes without testing their classes.

SMALLTALK
shapes inject: 0 into: [ :sum :s | sum + s area ].
JS Check exercises 7 and 8

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reflection and metaclasses

9. Class chain. Write a block that returns the names of all superclasses of OrderedCollection.

SMALLTALK
OrderedCollection allSuperclasses collect: [ :c | c name ].
"or walk it yourself:"
| c names |
c := OrderedCollection.
names := OrderedCollection new.
[ c notNil ] whileTrue: [ names add: c name. c := c superclass ].
names.

10. Class-side constructor. Add Point3D class >> x: x y: y z: z that returns an initialized instance. Why is it a class-side method? Explain in a sentence.

Answer. The message is sent to the class (Point3D x: 1 y: 2 z: 3), so it must live in the metaclass Point3D class, as explained in Classes Are Objects and Metaclasses.

SMALLTALK
Point3D class >> x: ax y: ay z: az
    ^ self new setX: ax y: ay z: az

Tests and design

11. Write tests first. Write an SUnit test for a Temperature class with fromCelsius: and fahrenheit: 0 C is 32 F, 100 C is 212 F. Then implement it.

SMALLTALK
TemperatureTest >> testFreezing
    self assert: (Temperature fromCelsius: 0) fahrenheit equals: 32

TemperatureTest >> testBoiling
    self assert: (Temperature fromCelsius: 100) fahrenheit equals: 212
JS Check exercise 11

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Floating-point numbers are inexact in general, so compare them with a tolerance (assert: a closeTo: b) rather than =. In Smalltalk, integer and fraction arithmetic is exact: 37 * 9 / 5 + 32 gives the fraction 493/5. See SUnit for assertions.

12. Observer. Make a Thermostat announce TemperatureChanged when its value changes, and subscribe a display. Sketch the classes and the subscription code, then compare with announcements.

SMALLTALK
Announcement subclass: #TemperatureChanged
    instanceVariableNames: 'value'
    package: 'Practice'.

Thermostat >> value: aNumber
    value := aNumber.
    announcer announce: (TemperatureChanged new value: aNumber)

thermostat announcer when: TemperatureChanged do: [ :a | Transcript show: a value printString; cr ].

Where to go next

If you finished all twelve, you are ready to build something real: extend the text adventure engine, grow your interpreter from the message interpreter project, or put a REST face on a model with Teapot.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does 2 + 3 * 4 return in Smalltalk?

    Binary messages go left to right: (2 + 3) * 4 = 20.
  2. 2. Where does Point3D class >> x:y:z: live?

    It is sent to the class object, so it belongs to the metaclass.
  3. 3. Why use self subclassResponsibility in Shape>>area?

    It marks the method abstract and signals an error if it is ever reached.
  4. 4. What is the best first step on a new feature?

    A failing test states the goal and drives the implementation.

Summary

  • Smalltalk precedence is unary, binary (left to right), keyword.
  • Blocks, collections and dictionaries solve most small tasks; classes model larger ones.
  • Class-side constructors live in metaclasses; abstract methods use subclassResponsibility.
  • Write tests first and use announcements for observers.
  • Solutions are read-only Smalltalk; JavaScript checks are stand-ins.

Next: Back to the Smalltalk track

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.