Smalltalk

From Exampleproblems

Jump to: navigation, search

Smalltalk is an object-oriented, dynamically typed, reflective, programming language designed at Xerox PARC by Alan Kay, Dan Ingalls, Ted Kaehler, Adele Goldberg, and others during the 1970s, influenced by Sketchpad and Simula. The language was generally released as Smalltalk-80 and has been widely used since. Smalltalk is in continuing active development, and has gathered a loyal community of users around it.

Contents

History

Smalltalk was invented by a group of researchers led by Alan Kay at Xerox Palo Alto Research Center; Alan Kay designed the system, which Dan Ingalls implemented. The first implementation, known as Smalltalk-71, was created in a few mornings on a bet that a programming language based on the idea of message passing inspired by Simula could be implemented in "a page of code". A later version actually used for research work is now known as Smalltalk-72. Its syntax and execution model were very different from modern Smalltalk, so much so that it could be considered a different language.

After significant revisions which froze some aspects of executional semantics to gain performance, the version known as Smalltalk-76 was created. This version added inheritance, featured syntax much closer to Smalltalk-80, and had a development environment featuring most of the tools now familiar to Smalltalkers.

Smalltalk-80 added metaclasses, something which helps keep the "everything is an object" statement true by associating properties and behavior with individual classes (for example, to support different ways of creating instances). Smalltalk-80 was the first version made available outside of PARC, first as Smalltalk-80 Version 1, given to a small number of companies (HP, Apple Computer, Tektronix, and DEC) and universities (UC Berkeley) for "peer review" and implementation on their platforms. Later (in 1983) a general availability implementation, known as Smalltalk-80 Version 2, was released as an image (platform-independent file with object definitions) and a virtual machine specification.

Two of the currently popular Smalltalk implementations are descendants of those original Smalltalk-80 images. Squeak is an open source implementation derived from Smalltalk-80 Version 1 by way of Apple Smalltalk. VisualWorks is derived from Smalltalk-80 version 2 by way of Smalltalk-80 2.5 and ObjectWorks (both products of ParcPlace Systems, Xerox PARC spin-off company formed to bring Smalltalk to the market). As an interesting link between generations, here is a screenshot of Smalltalk-80 version 2 image running on Hobbes, a Smalltalk-80 VM implemented in VisualWorks.

IBM has indicated that VisualAge Smalltalk will be supported by partner company (and VisualAge implementors) Instantiations. Cincom, Dolphin, GemStone, and other vendors continue to sell Smalltalk environments. The open Squeak implementation has a relatively active community of developers, including many of the original Smalltalk community. GNU Smalltalk is a free (GPL) implementation of Smalltalk from the GNU project. There is even a Smalltalk cross-compiler ([1]) for the PalmPilot which runs on Windows (though it seems that development may have stagnated in recent years). More recently, Ruby has reimplemented many of Smalltalk's ideas, providing a more traditional syntax, an extensive standard library, while also borrowing concepts from other languages such as Perl and Python. There is also a high-performance JITted modular Smalltalk implementation designed for scripting called S# (SSharp [2]) which supports an extended dialect of Smalltalk .

Object-Oriented Programming

In Smalltalk, an 'object' is an instantiation of a class, and every value is an object. In contrast to many other languages (eg, Java), even primitive types such as integers and booleans are classes in Smalltalk. Objects in Smalltalk can do exactly three things:

  • Send a message to itself or another object.
  • Receive a message from itself or another object.
  • Hold state (references to other objects).

Importantly, an object cannot inspect or change the state of another object, and all communication is done by message passing. Any message can be sent to any object: the receiver determines whether that message is appropriate. Classes are also objects, and are instantiations of their metaclass. Each metaclass instantiates the class 'Metaclass', facilitating lexical closures. A code block can also be represented as a smalltalk object.

Syntax

Only a handful of behaviors are implemented in the language's minimalist syntax.

Variable Declarations

Variable declarations in Smalltalk are enclosed by vertical bars, for example:

| aString |

Declares the variable aString. Multiple variables may be declared within one set of bars, so:

| aString vowels |

Value Assignment

A variable is assigned a value via the ':=' syntax. So:

vowels := 'aeiou'

Assigns the value 'aeiou' to the previously declared vowels variable.

Message Passing

Smalltalk message passing is achieved by the syntax

object message

The result of this message can be assigned to a variable:

foo := bar baz

Sends the message 'baz' to the object 'bar', and assigns the returned value to the object 'foo'. A message can also have arguments, consisting of one or more objects. This is achieved with:

object message: argument1

Multiple arguments are separated by keyword parts which are delimited with colons, as in:

object keywordPart1: arg1 keywordPart2: arg2 ...

Concrete examples are:

a at:1 put:'hello'

or:

anArray indexOf: 0 startingAt: 5

Finally, most of the special (non-alphabetic) characters can be used as binary messages. These allow for the well known mathematical and logical operators to be written in a traditional form:

4 * a

Sends the message "*" to the receiver "4" passing the value of "a" as argument. Notice, that the Smalltalk language itself does not imply any semantic meaning of those operators. The outcome of the above is only defined by how the receiver of the message (in this case a Number-object) responds to the "*"-message. Thus, traditional operator-overloading is a side effect of this mechanism.

Code Blocks

A block of code can be expressed as a literal object. This is achieved with square brackets:

[ :params | <message-expressions> ]

Where :params is the list of parameters the code can take. This means that the Smalltalk code:

[:x | x + 1]

is equivalent to:

f(x) = x + 1

Technically, the resulting block object is a closure. It can (at any time) access the variables of its enclosing lexical scopes. Just like any other object, references to blocks can be passed as argument, returned as value or stored as state. Eventually, blocks are asked to execute their code by sending them a "value"-message.

Control Structures

Smalltalk control structures are notably absent from the language syntax. These are instead implemented as messages sent to objects. For example, conditional execution is implemented by sending the message ifTrue: to a Boolean object, with the block of code to be executed if and only if the Boolean is True as the message argument. The following code demonstates this.

result := a > b
    ifTrue:[ 'greater' ]
    ifFalse:[ 'less' ]

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: [:aCharacter | aCharacter isVowel].

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.

Collection>>select: aBlock
| newCollection |
newCollection := self species new.
self do: [:each | 
    (aBlock value: each) 
        ifTrue: [newCollection add: each]].
^newCollection

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 mesage "value: each",) the selection block (referenced by the parameter "aBlock," and defined by the block literal "[:aCharacter | aCharacter isVowel]",) 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, we can also use it like this:

| rectangles aPoint|
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: [:aRect | aRect containsPoint: aPoint].

Classes

This is a stock class defintion:

Object subclass: #MessagePublisher
    instanceVariableNames: ''
    classVariableNames: ''
    poolDictionaries: ''
    category: 'Smalltalk Examples'

Often, most of this definition will be filled in by the environment.

Methods

When an object receives a message, a method matching the message name is invoked. The following code:

publish
    Transcript show: 'Hello, World!'

Defines a method publish, and so defines what will happen when this object receives the 'publish' message. Note that the pairing of a message with a method is done by the object at runtime (while in many languages this is determined statically at compile time).


Instantiating Classes

The following code:

MessagePublisher new

Creates (and returns) a new instantiation of the MessagePublisher class. This is typically assigned to a variable:

publisher := MessagePublisher new

However, it is also possible to send a message to a temporary, anonymous object:

MessagePublisher new publish

Hello World Example

In the following code, the message "show:" is sent to the object "Transcript," with the String literal 'Hello, world!' as its argument. Invocation of the "show:" method causes the characters of its argument (the String literal 'Hello, world!') to be displayed in the transcript ("console") window.

   Transcript show: 'Hello, world!'.

Note that you need to have a Transcript window open in order to see the results of this example.

Image-based interpretation

Most Smalltalk systems are Image based instead of file based. Starting a Smalltalk image returns it entirely to its previous state, much like the hibernation mode of a laptop computer. Many popular programming languages are instead file based. Lisp is another language which is often implemented in a image based environment. This has many benefits such as debugging production issues offline, with full program state at the time of the error.

Level of Access

Everything in Smalltalk is available for modification from within a running program. This means that, for example, the IDE can be changed in a running system, without restarting it. In some implementations, you can also change the syntax of the language, or the garbage collection implementation.

Just-in-Time Compilation

Smalltalk programs are usually compiled to bytecode, which is then interpreted by a virtual machine or dynamically translated into machine-native code. This mechanism has been adopted by languages such as Java and C#.

Implementations

External links

Books


Template:Major programming languages smallde:Smalltalk (Programmiersprache) es:Smalltalk fr:Smalltalk it:Smalltalk nl:Smalltalk ja:Smalltalk pl:Smalltalk pt:Smalltalk ru:Smalltalk sk:Smalltalk fi:Smalltalk sv:Smalltalk uk:Smalltalk zh:Smalltalk

Argan Oil
Natural Skin Care
Organic Skin Care
visitor stats