Help - Glossary - B - Block

Blocks are one of the beauties of Squeak. They idea is derived from Lambda Calculus, and comes to this: Any expression of Squeak that Squeak can evaluate can be put inside a block with variables. The block then can be used as a function and called with appropriate values. Here are two simple examples you can use with Cmd-p:

[:x | 2*x] value: 25.
[:x :y | x squared + y squared] value: 3 value: 4.

This is a great tool for programming.

What's inside a block - marked by square brackets are - one or more Smalltalk expressions. A block is itself an expression, and returns its value when calculated. It also forms an object when assigned to a variable. Thus e.g.

| doubler |
doubler := [:x | 2*x].
doubler value: 50

The parameters of a block are the terms in it that occurs once more to the left of " | " with a prefixed colon to mark them as parameters.

Blocks themselves can have local variables as in

| sum adder interim |
sum := 0.
adder := [:n | interim := sum+n. sum:= interim].
[sum < 11] whileTrue: [adder value: 1].
adder value: 1.
^sum

Alternatively:

| sum adder |
sum := 0.
adder := [:n | | interim | interim := sum+n. sum:= interim].
[sum < 11] whileTrue: [adder value: 1].
adder value: 1.
^sum

And Blocks may be passed as parameters of methods. See e.g. SortedCollection.

It should be noted that Blocks in Squeak-as-is have a few shortcomings. These are too technical to list here, and in fact a new virtual machine has been designed that overcomes these shortcomings.

Glossary - B