REFERENCE · Pharo course

Reference Card

Blocks & the Iteration Vocabulary

A block is an object. Every loop is a message that takes a block. Learn six selectors and you can process any data.

Blocks — deferred computation

FormMeaningRun it
[ 2 + 2 ]a zero-arg block (not yet run)[ 2 + 2 ] value → 4
[ :x | x * x ]one parameter[ :x | x*x ] value: 6 → 36
[ :a :b | a + b ]two parametersvalue: 3 value: 4 → 7

Making collections

#(1 2 3 4 5)          "literal Array"
{ 1+1. 2 factorial }  "dynamic Array (evaluated)"
1 to: 100             "an Interval, iterable"
OrderedCollection new "growable; addFirst:/add:/removeFirst"

The six you use daily

SelectorDoesExample → result
do:side-effect for each; returns the receiver#(1 2 3) do: [:e | ... ]
collect:transform each (map)#(1 2 3) collect: [:x | x*x] → #(1 4 9)
select:keep those that pass (filter)#(1 2 3 4) select: [:x | x even] → #(2 4)
reject:drop those that pass#(1 2 3 4) reject: [:x | x even] → #(1 3)
detect:first match (error if none)#(1 2 3) detect: [:x | x>1] → 2
detect:ifNone:first match or fallback... detect: [:x | x>9] ifNone: [0] → 0
inject:into:fold to one value (reduce)(1 to: 100) inject: 0 into: [:a :e | a+e] → 5050
Read the shapes collect: same size, transformed. select:/reject: same-or-smaller, same elements. detect: one element. inject:into: one accumulated value; the block is [:accumulator :each | ...] and the seed comes after inject:.

Dictionary — key → value

MessageDoes
d at: #a put: 3store 3 under key #a
d at: #aread (error if key missing)
d at: #a ifAbsent: [ 0 ]read, or block's value if missing
d at: #a ifAbsentPut: [ X ]get-or-create: store & return X if missing
d keys   d valuesall keys / all values (iterable)
d associationsDo: [ :as | as key … as value ]iterate key+value pairs
d includesKey: #atest membership

Handy extras

coll size          coll isEmpty          coll includes: 3
coll sum           coll max              coll average
coll sorted        coll sort: [:a :b | a > b]
coll do: [ :e | ... ] separatedBy: [ ... ]

Companion to Lesson 0002. Ask your teacher to expand any row into live practice in your image.