An Introduction to Smalltalk

By Wenling Chen

[History] [Features] [Syntax] [Example] [Reference]

Smalltalk is a pure Object-Oriented Programming Language implemented in many OS. Its syntax is very simple and the code is very readable. It has no explicit pointers and manual memory management; all these are done by garbage collection. The design concepts of Smalltalk are found in many popular programming languages such as Ruby, Java, and C++.

History [Top]

Smalltalk was created in the early 1970s by Alan Kay at Xerox’s Palo Alto Research Center (PARC). Follows Simula (1966), Smalltalk was one of the first object-oriented programming languages. The Smalltalk is written almost entirely in Smalltalk.

·         1967 – Simula 67

·         1972 – Smalltalk 72 was created. It based on the Simula 67

·         1976 – Smalltalk 76 was released. It was completely an OOPL

·         1980 – Smalltalk-80 became the first commercial release

Features [Top]

·         Smalltalk is a small language; The rules of the language are very simple

o   No reserved words

o   No control structure statements

o   No built-in types

o   No operators

·         The underlying concept are uniformly applied

o   Every type in Smalltalk is a class (no primitive type).

o   Every expression is a message expression

·         The code can be very compact and readable

·         Dynamically typed: find its definition at run-time

·         Strong typed: it can do only it was programmed

·         Statically scoped

·         Single inheritance model

 

Syntax [Top]

Literals

Literals are pretty straight forward in Smalltalk. Notice that the space character cannot be part of a symbol; an array can have different types of elements and inner array does not need the # sign.

Character            dollar sign,                                          $1, $a, $$

String                    use single quote                               ‘print this‘

Symbols               unique instance of strings:           #BinaryTree, #at:put:

Array                     #(), begin with 1                               #($1  $a  $$  ‘Tree pre-order’  ($e  $f) )

Comments          use double quote                            “comments”

Special objects  nil,  true,  false,  self,  super

Variable declarations

There are mainly two kind of variable: temporary variables and instance variables. Temporary variables are declared inside methods by using a vertical bar at the beginning and the end; Instance variables (there are also class variables) are declared inside class definitions.  For example, the following declared two temporary variables var1 and var2:

    methodName: params

        | var1  var2  |

        Statements for this method.

Assignments

Assignment message use colon and equal. It evaluates the right hand side expression and assigns the object reference to the left hand side.

sum := a + b.

root := left := right := nil.

Message expressions

Running a Smalltalk program is all about passing messages. Smalltalk begin execution by sending out a message to an object and the object executes the corresponding methods. The notation of messages is: receiver selector arguments. For example:


    3 + 9.  “This sends message + 9 to an object 3.”


Here 3 is the receiver,  + is a selector and 9 is an argument.

 

Unary expressions

Unary expressions do not have arguments. In following example, x is the receiver and sqrt is selector.

x sqrt.

Binary expressions

Binary expressions in Smalltalk are similar to other languages. However, Smalltalk is different because it always evaluates expressions from left to right.

   1 + 2 * 3.    “return 9”
    3 < 4 + 5.    “error, the receiver is 3 < 4, it does not know how to + 5”

Keyword expressions

A keyword expression in Smalltalk is specified by one or more keyword and parameter pairs. The colon sign separate the key word and the parameter for each pairs; a space separate on pair from another. The number of keywords in a keyword expression is equal to the number of parameters. For example:

 

 1.2 raisedTo: 3.   “raisedTo: is the selector”
    anArray := #(1 2 3 4 5 6 7 8 9).
    anArray  at: 1 + 2 * 3  put: 5 sqrt.  “at:put: is the selector”

 

Parsing order

 Parsing order is very simple in Smalltalk. From highest to lowest is ( ),  unary,  binary,  keyword, left to right.

anArray  at: 1 + 2 * 3  put: 5 sqrt. “This expression is equivalent to  anArray at: ((1+2)*3) put: (5 sqrt)”

Operator

Operators are not part of Smalltalk language. Instead, operators are defined in each receiving object’s class. You can also define or overload operators.

+ - *

Arithmetic operators

/

Fraction

//

Integer division

\\

Modulus

<  <=  >  =>

Ordering comparisons

&  |

Logical operators AND and OR

==  ~~

Reference equal or not equal

=  ~=

Logical equal or not equal

,

Concatenation of strings, arrays

 

Blocks

Blocks are powerful features of Smalltalk. A code block is an instance of class BlockClosure; it can be used as a variable – be assigned to another variable or returned as a return value. Because Smalltalk is static scope, all variables inside a code block are evaluated base on their locations of definition, not the execution locations. A block definition use the [] notation: [ :params | <message expressions> ]
[ ‘abcd’ asUppercase ] value.   “send the message value  to a code block execute the block” aBlock := [ :a :b | a*a + b*b ].  “define a code block and assign it to a variable”
(aBlock value: 3  value: 4) sqrt  “execute the above code block with arguments 3 and 4”

Control flow

If-then-else statement

Use message  ifTrue:  ifFalse:

“test if you are a teenager”

| age |

age := 14.

(age >= 13) & (age <= 19)

    ifTrue: [ ^’You are a teenager’ ]

    ifFalse: [ ^’You are not a teenager’ ]

 

( a > b )

    ifTrue: [ a := a – b]

    ifFalse: [ a := a + b]

a := ( a > b)

        ifTrue: [ a – b ]

        ifFalse: [ a + b ]

Iteration

Use message whileTrue:, whileFalse:

find: x at: t

“find x in the binary tree t”

                | tmp |

                tmp := t.

                [tmp isNil not] whileTrue:

                                                [tmp > x ifTrue: [tmp := tmp left].

                                                tmp < x ifTrue: [tmp := tmp right].

                                                tmp = x ifTrue: [^tmp]].

                ^nil

Use message do:

includes: anObject

                "Answer whether anObject is one of the receiver's elements."

 

                self do: [:each | anObject = each ifTrue: [^true]].

                ^false

Message to: do:

 

“test to:do:”

 

“declare a temporary variable”

| s |     

 

“create a set object  for s”

s := Set new.   

 

“add number 1..25 to the set s”

1 to: 25 do: [ :each | s add: each ]. 

 

“select those numbers which can be divided by 3”

s select:  [ :each | each \\ 3 = 0 ].

 

“Set (18 3 21 6 24 9 12 15)”

 

Class definition

Class definition is accomplished by sending a message to a super class or the NameSpace class. The following code was generated by Cincom Smalltalk IDE which defines a class Node. Most Smalltalk IDEs can generate code templates for class definitions, you don’t need to remember the exactly syntax of the message.

Smalltalk.MyTree defineClass: #Node

                superclass: #{Core.Object}

                indexedType: #none

                private: false

                instanceVariableNames: 'value left right height '

                classInstanceVariableNames: ''

                imports: ''

                category: 'BinaryTree'

 

Inheritance

Use message superclass: or subclass, as the above example shown. Many Smalltalk IDEs can generate code templates for class creation and other structures.

Method definition

A corresponding method gets executed when a message was sent to a receiver object.  A method signature is a list of selector-parameter pair separated by spaces.

        “define a method cube:, which take a parameter i”

        cube: i
                ^i * i * I    “^ means return to the caller”

Instance creation

Smalltalk class library use the message new to create an Instance of a class. You can define you own new method or you can define other names instead of new for instance creation.

aTree := BinaryTree new.    “create an instance of class BinaryTree”

Example [Top]

Install VisualWorks Smalltalk
To use the example, you need to downloand and install Cincom VisualWorks from www.cincom.com. A free non-commercial version is available (532MB on windows).

Open the example source code
Open Cincom VisualWorks, click menu [File]->[File Browser], then select file name “BinaryTree.st”, right click on it and select [File In], then close the File Browser.

 

Run the example program
In the main VisualWorks window (the Launcher), click on menu [Painter]->[Resource Finder], then select the class name “MyTree.BTreeEditor”, then click button [start].

To browse the source code, click button [Browse], or button [Edit] to edit the GUI.

Reference & resources [Top]

Beginners guide to Smalltalk: http://www.whysmalltalk.com/beginnersguide/guide.htm

 

Online tutorials: Smalltalk and object-oriented tutorials http://www.whysmalltalk.com/tutorials/index.htm

 

Cincom Smalltalk home page: podcasts, screencasts and blogs http://www.cincomsmalltalk.com/userblogs/cincom/blogView

 

Software download:  Cincom’s VisualWorks http://smalltalk.cincom.com/downloads/index.ssp

 

GNU Smalltalk: A free implementation of the Smalltalk-80 language http://smalltalk.gnu.org/

 

Articles, papers, and news about Smalltalk http://www.smalltalk.org

 

A developer tell you why Smalltalk rocks http://www.xprogramming.com/xpmag/BowlingForSmalltalk.htm

 

Free books online: http://www.iam.unibe.ch/~ducasse/FreeBooks.html