Blocks
Code objects, evaluated by being sent value .
- acc: bankAccount copy.
- acc balance: 100.
- b:··[acc deposit: 50].
- acc balance.··"returns 100"
- b value.
- b value.
- acc balance.··"returns 200"
Can take arguments (evaluated with value:, value:With:, value:With:With:, ...)
- adder: [| :x. :y | x + y].
- adder value: 3 With: 4 "returns 7"
Used to implement control structures, e.g., if-then-else:
- In true:
- ifTrue: t False: f = (t value)
- In false:
- ifTrue: t False: f = (f value)
- Example of use:
- x != 0 ifTrue: [x reciprocal] False: 0
Other examples:
- [i < j] whileTrue: [i: i * 2].
- 20 do: [| :n | n printLine].
- vec do: [| :el | el printLine]
|
Blocks
A block is a kind of code object. It differs from a method in that its code is evaluated
only when the block itself is sent a value message. Blocks are similar to anonymous
functions (lambdas) in Lisp and functional languages. The syntax for a block is like
that of a method, except that brackets are used instead of parentheses:
acc: bankAccount copy.
acc balance: 100.
b: [acc deposit: 50].
acc balance. "returns 100"
b value.
b value.
acc balance. "returns 200"
Blocks can take arguments, using the same syntax as methods. A 1-argument block
is evaluated using the message value:, a 2-argument block with value:With:, a 3-
argument block with value:With:With:, etc.
adder: [| :x. :y | x + y].
adder value: 3 With: 4 "returns 7"
Blocks are used to implement control structures. For example, an if-then-else
statement is implemented by having ifTrue:False: methods in true and false. In true,
the definition is:
ifTrue: t False: f = (t value)
whereas in false the definition is:
ifTrue: t False: f = (f value)
A typical usage is then:
x != 0 ifTrue: [x reciprocal] False: 0
(In defaultBehavior, value is defined to return self.)
In Self 4.0, every block must appear as a literal within a method. Blocks
may be nested. In contrast, methods may not be nested. A block is evaluated in the
context of the surrounding method/block.
|