Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Collections and Blocks

Iteration and Enumeration in Smalltalk: do:, collect:, select:, inject:into:

Master the Smalltalk enumeration protocol: do:, collect:, select:, reject:, detect:, inject:into:, anySatisfy:, with:do:, groupedBy: and sorting with blocks, and learn to build your own iterators.

In Smalltalk you rarely write a loop with an index. You ask the collection to iterate for you, giving it a block that says what to do with each element. The same small set of messages works on arrays, ordered collections, sets, dictionaries, intervals and strings, and learning them is one of the biggest productivity boosts in the language. This lesson shows each message, what it answers, and how to choose.

Smalltalk code in this lesson is read-only; JavaScript stand-ins are runnable.

do: runs a block for every element

SMALLTALK
#(3 1 2) do: [ :each | Transcript show: each printString; cr ].

do: is the base operation, defined by every collection. It is used for side effects and answers the receiver. Variants:

SMALLTALK
#(3 1 2) do: [ :each | ... ] separatedBy: [ Transcript show: ', ' ].
#(3 1 2) doWithIndex: [ :each :i | ... ].       "also keysAndValuesDo:"
#(3 1 2) reverseDo: [ :each | ... ].
#(1 2 3) with: #(10 20 30) do: [ :a :b | ... ]. "walk two collections together"

collect: transforms

collect: builds a new collection with the block applied to each element:

SMALLTALK
#(1 2 3) collect: [ :n | n * n ].               "-> #(1 4 9)"
#('a' 'bb') collect: [ :s | s size ].           "-> #(1 2)"
(1 to: 5) collect: [ :i | i factorial ].        "-> #(1 2 6 24 120)"

The kind of collection you get back matches the receiver where possible (an Array answers an Array, an OrderedCollection an OrderedCollection, a Set a Set).

select: and reject: filter

SMALLTALK
#(1 2 3 4 5 6) select: [ :n | n even ].    "-> #(2 4 6)"
#(1 2 3 4 5 6) reject: [ :n | n even ].    "-> #(1 3 5)"
(1 to: 20) select: [ :n | n isPrime ].     "-> #(2 3 5 7 11 13 17 19)"

detect: finds one element

SMALLTALK
#(3 8 5) detect: [ :n | n > 4 ].                       "-> 8"
#(3 8 5) detect: [ :n | n > 10 ] ifNone: [ nil ].      "-> nil"
#(3 8 5) detect: [ :n | n > 10 ].                      "-> error: element not found"

Always supply ifNone: when the answer may not exist.

inject:into: folds

inject: start into: aBlock threads an accumulator through the collection, like reduce:

SMALLTALK
#(1 2 3 4) inject: 0 into: [ :sum :n | sum + n ].        "-> 10"
#(1 2 3 4) inject: 1 into: [ :prod :n | prod * n ].      "-> 24"
#('a' 'bb' 'ccc') inject: '' into: [ :acc :s | acc, s ]. "-> 'abbccc'"

Convenience messages cover the common folds: sum, max, min, average, detectMax:, detectMin:, sumNumbers: (names differ a little between Pharo versions).

SMALLTALK
#('pear' 'fig' 'banana') detectMax: [ :s | s size ].    "-> 'banana'"
#(1 2 3) sum: [ :n | n * 2 ].                           "-> 12"

Questions about a collection

SMALLTALK
#(2 4 6) allSatisfy: [ :n | n even ].    "-> true"
#(2 4 7) anySatisfy: [ :n | n odd ].     "-> true"
#(2 4 7) noneSatisfy: [ :n | n > 10 ].   "-> true"
#(2 4 7) count: [ :n | n even ].         "-> 2"
#(2 4 7) includes: 4.                    "-> true"
#() isEmpty.                             "-> true"

Sorting and grouping

SMALLTALK
#(3 1 2) sorted.                                    "-> #(1 2 3)"
#('pear' 'fig' 'banana') sorted: [ :a :b | a size <= b size ].
#('pear' 'fig') sorted: #size ascending.           "sort by a key in recent Pharo"
#(3 1 2) asSortedCollection: [ :a :b | a >= b ].
#(1 2 3 4 5 6) groupedBy: [ :n | n even ].         "-> a Dictionary true/false -> elements"

Chaining

Because each message answers a collection, they combine into pipelines:

SMALLTALK
(1 to: 20)
    select: [ :n | n isPrime ]
    thenCollect: [ :n | n squared ].

#('Ada' 'Grace' 'Alan')
    select: [ :name | name first = $A ]
    thenCollect: [ :name | name asUppercase ].

select:thenCollect: does it in one pass; (x select: ...) collect: ... does two and creates an intermediate collection. For huge data use lazy iterators or Streams.

Never modify while iterating

Adding or removing elements of a collection while iterating over it leads to skipped elements or errors. Iterate over a copy (list copy do: [...]) or collect the elements to remove first and remove afterwards (list removeAll: toRemove), or use removeAllSuchThat::

SMALLTALK
list removeAllSuchThat: [ :each | each isNil ].

Writing your own iterator

Any class can offer do: and inherit a rich protocol. If you subclass Collection and implement do:, you get collect:, select:, inject:into:, detect: and many others without writing them:

SMALLTALK
Collection << #Countdown
    slots: { #from };
    package: 'Demo'.

Countdown >> do: aBlock
    from to: 1 by: -1 do: aBlock

Countdown new ... do: now supports all the above messages. (A Collection subclass also wants add:, remove:ifAbsent:, size; a read-only view can stay with do:.) This is the template method pattern at work: the general algorithms are written in terms of do:.

JS Stand-in: the enumeration protocol

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

No output.

JS Stand-in: your own collection gets everything from do:

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

No output.

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does #(1 2 3) collect: [ :n | n * 2 ] answer?

    collect: builds a new collection from the block results.
  2. 2. What is the result of #(1 2 3 4) inject: 0 into: [ :sum :n | sum + n ]?

    inject:into: threads an accumulator through the elements, here adding them up.
  3. 3. Why should you pass ifNone: to detect: when the element may be missing?

    detect: without ifNone: raises an error when no element matches.
  4. 4. What should you do before removing elements while iterating?

    Modifying a collection during its own iteration skips elements or fails; iterate a copy or use the bulk removal message.
  5. 5. If you subclass Collection and implement do:, what do you get?

    Collection implements its whole enumeration protocol in terms of do:.

Summary

  • Use do: for side effects, collect: to transform, select:/reject: to filter, detect:ifNone: to find, inject:into: to fold.
  • anySatisfy:, allSatisfy:, count: and includes: answer questions about elements.
  • Sort with sorted: or asSortedCollection:, group with groupedBy:, combine messages into pipelines.
  • Do not change a collection while you iterate it; iterate a copy.
  • A class that implements do: can inherit the whole protocol from Collection.

Next: Strings, Symbols and Streams