Smalltalk - Control Structures

Control Structures

Control structures do not have special syntax in Smalltalk. They are instead implemented as messages sent to objects. For example, conditional execution is implemented by sending the message ifTrue: to a Boolean object, passing as an argument the block of code to be executed if and only if the Boolean receiver is true.

The following code demonstrates this:

result := a > b ifTrue: ifFalse:

Blocks are also used to implement user-defined control structures, enumerators, visitors, pluggable behavior and many other patterns. For example:

| aString vowels | aString := 'This is a string'. vowels := aString select: .

In the last line, the string is sent the message select: with an argument that is a code block literal. The code block literal will be used as a predicate function that should answer true if and only if an element of the String should be included in the Collection of characters that satisfy the test represented by the code block that is the argument to the "select:" message.

A String object responds to the "select:" message by iterating through its members (by sending itself the message "do:"), evaluating the selection block ("aBlock") once with each character it contains as the argument. When evaluated (by being sent the message "value: each"), the selection block (referenced by the parameter "aBlock", and defined by the block literal ""), answers a boolean, which is then sent "ifTrue:". If the boolean is the object true, the character is added to a string to be returned. Because the "select:" method is defined in the abstract class Collection, it can also be used like this:

| rectangles aPoint collisions | rectangles := OrderedCollection with: (Rectangle left: 0 right: 10 top: 100 bottom: 200) with: (Rectangle left: 10 right: 10 top: 110 bottom: 210). aPoint := Point x: 20 y: 20. collisions := rectangles select: .

Read more about this topic:  Smalltalk

Famous quotes containing the words control and/or structures:

    The mind is the greatest of all human forces. Control the mind and you control the body.
    Griffin Jay, Randall Faye, and Lew Landers. Armand Tesla (Bela Lugosi)

    The philosopher believes that the value of his philosophy lies in its totality, in its structure: posterity discovers it in the stones with which he built and with which other structures are subsequently built that are frequently better—and so, in the fact that that structure can be demolished and yet still possess value as material.
    Friedrich Nietzsche (1844–1900)