typestar

select and collect in Smalltalk

Keep, transform, find: the collection trio.

"select keeps, collect transforms, detect finds the first."
| runs longRuns doubled |
runs := #(120 340 85 500 210).

longRuns := runs select: [:n | n > 150].
Transcript show: 'Long runs: ', longRuns printString; cr.

doubled := runs collect: [:n | n * 2].
Transcript show: 'Reprints: ', doubled printString; cr.

Transcript show: (runs detect: [:n | n > 400]) printString; cr.
Transcript show: (runs detect: [:n | n > 900] ifNone: [0])
    printString; cr.
Transcript show: (runs reject: [:n | n < 200]) printString; cr.

How it works

  1. select: keeps what the block approves.
  2. collect: maps every element to a new collection.
  3. detect:ifNone: finds the first hit or falls back.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
517
Tokens
116
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 127 seconds.

Type this snippet

Step 1 of 4 in Enumeration, step 14 of 31 in Language basics.

← Previous Next →