Introduction to Blocks

Damien Cassou, St├ęphane Ducasse and Luc Fabresse http://stephane.ducasse.free.fr

Blocks

Blocks are:

Block Definition

A block is defined by [ ]

[ expressions. ... ]

Block Definition Does not Execute Code

( 1 / 0 )
-> Error
[ 1 / 0 ]
> [ 1 /0 ]
[ 1 / 0 ].
1 + 2 
> 3

Executing a Block

Executing a block is done explicitly through value

[ 2 + 6 ] value
> 8
[ 1 / 0 ] value
> Error

A Block with 1 Argument

A block can take arguments (just like methods)

[ :x | x + 2 ]
[ :x | x + 2 ] value: 5
> 7

Block Execution Value

Block execution returns the value of the last expression

[ :x |
  x + 33.
  x + 2 ] value: 5
> 7

Blocks can be Stored

| add2 |
add2 := [ :x | x + 2 ].

add2 value: 5.
> 7

add2 value: 33
> 35

Defining a Block with 2 Arguments

Example:

[ :x :y | x + y ]

:x :y are block arguments

How to execute a block with two arguments?

[ :x :y | x + y ] ??? 5 7
> 12

Executing a Block with 2 Arguments

[ :x :y | x + y ] value: 5 value: 7
> 12

A Block with Temporary Variables

Blocks can define temp. variables (just like methods)

Collection>>affect: anObject when: aBoolean
  self do: [ :index | | args |
    args := ....
    aBoolean
      ifTrue: [ anObject do: args ]
      ifFalse: [ anObject doDifferently: args ] ].

Returning from a Block Returns from the Method

When a return ^ is executed in a block, computation exits the method defining the block

Integer>>factorial
  "Answer the factorial of the receiver."
  
  self = 0 ifTrue: [ ^ 1 ].
  self > 0 ifTrue: [ ^ self * (self - 1) factorial ].
  self error: 'Not valid for negative integers'
0 factorial
>1

42 factorial
>1405006117752879898543142606244511569936384000000000

A Design Advice

Summary on Blocks

[ :variable1 :variable2 ... |
  | tmp |
  expression1.
  ... variable1 ...
] value: ... value: ...

/