Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Smalltalk
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Syntax== {{more citations needed section|date=June 2014}} '''Smalltalk-80''' [[Syntax (programming languages)|syntax]] is rather minimalist, based on only a handful of declarations. In fact, there are only five "keywords" in Smalltalk, names of pseudo-variables with a special meaning: <code>true</code>, <code>false</code>, <code>nil</code>, <code>self</code>, and <code>super</code>. These are properly termed ''pseudo-variables'', identifiers that follow the rules for variable identifiers but denote bindings that a programmer cannot change. The <code>true</code>, <code>false</code>, and <code>nil</code> pseudo-variables are [[singleton pattern|singleton]] instances. <code>self</code> and <code>super</code> refer to the receiver of a message within a method activated in response to that message, but sends to <code>super</code> are looked up in the superclass of the method's defining class rather than the class of the receiver, which allows methods in subclasses to invoke methods of the same name in superclasses. The only built-in language constructs are message sends, assignment, method return, literal syntax for some objects, including block literals (closures). From its origins as a language for children of all ages, standard Smalltalk syntax uses punctuation in a manner more like English than mainstream coding languages. The remainder of the language, including control structures for conditional evaluation and iteration, is implemented on top of the built-in constructs by the standard Smalltalk class library. (For performance reasons, implementations may recognize and treat as special some of those messages; however, this is only an optimization and is not coded into the language syntax.). The pseudo-variable <code>thisContext</code> may have been added in some implementations, but is not mentioned in either Smalltalk-80 or ANSI Standard. Pseudo-variables in general realise arguments passed to messages or blocks, content of these variables is read-only and cannot be modified. The adage that "Smalltalk syntax fits on a [[postcard]]" may have originated in Alan Kay's original conception of the language, as related by him in practically every of tens or hundreds of public lectures, [[op. cit.]], or perhaps it could refer to a code snippet by [[Ralph Johnson (computer scientist)|Ralph Johnson]], demonstrating all the basic standard syntactic elements of methods:<ref>{{cite journal |last1=Ducasse |first1=Stéphane |title=Squeak: Une syntaxe minimaliste / Squeak: A minimalist syntax!|journal=Programmez! Le Magazine du Développement |date=2001 |volume=1 |url=https://rmod-files.lille.inria.fr/Team/Texts/Vulgarisations/Programmez/Art2-Eng-AminimalistSyntax.pdf |access-date=15 January 2024}}</ref><ref>{{cite web |last1=Ducasse |first1=Stéphane |title=Object-Oriented Design with Smalltalk — a Pure Object Language and its Environment |url=https://scg.unibe.ch/archive/lectures/DucasseLectures/Duca00y1SmalltalkLectures.pdf |website=Software Composition Group (University of Berne) |access-date=15 January 2024}}</ref> <syntaxhighlight lang="smalltalk"> exampleWithNumber: x | y | true & false not & (nil isNil) ifFalse: [self halt]. y := self size + super size. #($a #a 'a' 1 1.0) do: [ :each | Transcript show: (each class name); show: ' ']. ^x < y </syntaxhighlight> ===Literals=== The following examples illustrate the most common objects which can be written as literal values in Smalltalk-80 methods. Numbers. The following list illustrates some of the possibilities. <syntaxhighlight lang="smalltalk"> 42 -42 123.45 1.2345e2 2r10010010 16rA000 </syntaxhighlight> The last two entries are a binary and a hexadecimal number, respectively. The number before the 'r' is the [[radix]] or base. The base does not have to be a power of two; for example 36rSMALLTALK is a valid number equal to 80738163270632 decimal. Characters are written by preceding them with a dollar sign: <syntaxhighlight lang="smalltalk">$A</syntaxhighlight> Strings are sequences of characters enclosed in single quotes: <syntaxhighlight lang="smalltalk">'Hello, world!'</syntaxhighlight> To include a quote in a string, escape it using a second quote: <syntaxhighlight lang="smalltalk">'I said, ''Hello, world!'' to them.'</syntaxhighlight> Double quotes do not need escaping, since single quotes delimit a string: <syntaxhighlight lang="smalltalk">'I said, "Hello, world!" to them.'</syntaxhighlight> Two equal strings (strings are equal if they contain all the same characters) can be different objects residing in different places in memory. In addition to strings, Smalltalk has a class of character sequence objects named Symbol. Symbols are guaranteed to be unique—there can be no two equal symbols which are different objects. Because of that, symbols are very cheap to compare and are often used for language artifacts such as message selectors (see below). Symbols are written as # followed by a [[string literal]]. For example: <syntaxhighlight lang="smalltalk">#'foo'</syntaxhighlight> If the sequence does not include whitespace or punctuation characters, this can also be written as: <syntaxhighlight lang="smalltalk">#foo</syntaxhighlight> Arrays: <syntaxhighlight lang="smalltalk">#(1 2 3 4)</syntaxhighlight> defines an array of four integers. <syntaxhighlight lang="smalltalk">#((1 2 3 4) [1 2 3 4] 'four' 4.0 #four)</syntaxhighlight> defines a seven element array whose first element is a literal array, second element a byte array, third element the string 'four', and so on. Many implementations support the following literal syntax for ByteArrays: <syntaxhighlight lang="smalltalk">#[1 2 3 4]</syntaxhighlight> defines a ByteArray of four integers. And last but not least, blocks ([[anonymous function]] literals) <syntaxhighlight lang="smalltalk">[... Some smalltalk code...]</syntaxhighlight> The following takes two arguments and compares any two objects which can understand "less than", for example, numbers, and strings<syntaxhighlight lang="smalltalk">[:a :b| a < b]</syntaxhighlight> Blocks are explained in detail further in the text. Many Smalltalk dialects implement additional syntaxes for other objects, but the ones above are the essentials supported by all. ===Variable declarations=== The two kinds of variables commonly used in Smalltalk are instance variables and temporary variables. Other variables and related terminology depend on the particular implementation. For example, [[VisualWorks]] has class shared variables and namespace shared variables, while [[Squeak]] and many other implementations have class variables, pool variables and global variables. Temporary variable declarations in Smalltalk are variables declared inside a method (see below). They are declared at the top of the method as names separated by spaces and enclosed by vertical bars. For example: <syntaxhighlight lang="smalltalk">| index |</syntaxhighlight> declares a temporary variable named index which contains initially the value <code>nil</code>. Multiple variables may be declared within one set of bars: <syntaxhighlight lang="smalltalk">| index vowels |</syntaxhighlight> declares two variables: index and vowels. All variables are initialized. Variables are initialized to nil except the indexed variables of Strings, which are initialized to the null character or ByteArrays which are initialized to 0. ===Assignment=== A variable is assigned a value via the '<code>:=</code>' syntax. So: <syntaxhighlight lang="smalltalk">vowels := 'aeiou'</syntaxhighlight> Assigns the string <code>'aeiou'</code> to the formerly declared vowels variable. The string is an object (a sequence of characters between single quotes is the syntax for literal strings), created by the compiler at compile time. In the original Parc Place image, the glyph of the underscore character ⟨_⟩ appeared as a left-facing arrow ⟨←⟩ (like in the 1963 version of the [[ASCII]] code). Smalltalk originally accepted this left-arrow as the only assignment operator. Some modern code still contains what appear to be underscores acting as assignments, hearkening back to this original usage. Most modern Smalltalk implementations accept either the underscore or the colon-equals syntax. ===Messages=== The message is the most fundamental language construct in Smalltalk. Even control structures are implemented as [[message passing|message sends]]. Smalltalk adopts by default a [[dynamic dispatch]] and [[single dispatch]] strategy (as opposed to [[multiple dispatch]], used by some other object-oriented languages). There are three kinds of message sends, unary messages which have a single keyword, such as <syntaxhighlight lang="smalltalk" inline>class</syntaxhighlight> and <syntaxhighlight lang="smalltalk" inline>size</syntaxhighlight>, binary messages which for example are used for arithmetic, such as <syntaxhighlight lang="smalltalk" inline>a < b</syntaxhighlight>, <syntaxhighlight lang="smalltalk" inline>a ~= b</syntaxhighlight>, and keyword messages where a keyword followed by a colon precedes each argument in the message, so that <syntaxhighlight lang="smalltalk" inline>a between: b and: c</syntaxhighlight> sends the <syntaxhighlight lang="smalltalk" inline>#between:and:</syntaxhighlight> message to <code>a</code> with arguments <code>b</code> and <code>c</code>. Unary messages have higher precedence than binary messages, which have higher precedence than keyword messages, and evaluation is strictly left-to-right. There is no arithmetic precedence. <syntaxhighlight lang="smalltalk" inline>1 + 2 * 3</syntaxhighlight> evaluates to 9, not to 7. The following example sends the message 'factorial' to number 42: <syntaxhighlight lang="smalltalk">42 factorial</syntaxhighlight> In this situation 42 is called the message ''receiver'', while 'factorial' is the message ''selector''. The receiver responds to the message by returning a value (presumably in this case the [[factorial]] of 42). Among other things, the result of the message can be assigned to a variable: <syntaxhighlight lang="smalltalk">aRatherBigNumber := 42 factorial</syntaxhighlight> "factorial" above is what is called a ''unary message'' because only one object, the receiver, is involved. Messages can carry additional objects as ''arguments'', as follows: <syntaxhighlight lang="smalltalk">2 raisedTo: 4</syntaxhighlight> In this expression two objects are involved: 2 as the receiver and 4 as the message argument. The message result, or in Smalltalk parlance, ''the answer'' is supposed to be 16. Such messages are called ''keyword messages''. A message can have more arguments, using the following syntax: <syntaxhighlight lang="smalltalk">'hello world' indexOf: $o startingAt: 6</syntaxhighlight> which answers the index of character 'o' in the receiver string, starting the search from index 6. The selector of this message is "indexOf:startingAt:", consisting of two pieces, or ''keywords''. Such interleaving of keywords and arguments is meant to improve readability of code, since arguments are explained by their preceding keywords. For example, an expression to create a rectangle using a C++ or Java-like syntax might be written as: <syntaxhighlight lang="java">new Rectangle(100, 200);</syntaxhighlight> It's unclear which argument is which. By contrast, in Smalltalk, this code would be written as: <syntaxhighlight lang="smalltalk">Rectangle width: 100 height: 200</syntaxhighlight> The receiver in this case is "Rectangle", a class, and the answer will be a new instance of the class with the specified width and height. Finally, most of the special (non-alphabetic) characters can be used as what are called ''binary messages''. These allow mathematical and logical operators to be written in their traditional form: <syntaxhighlight lang="smalltalk">3 + 4</syntaxhighlight> which sends the message "+" to the receiver 3 with 4 passed as the argument (the answer of which will be 7). Similarly, <syntaxhighlight lang="smalltalk">3 > 4</syntaxhighlight> is the message ">" sent to 3 with argument 4 (the answer of which will be false). The programmer is free to define new binary selectors just as they are free to define novel unary and keyword messages. Notice, that the Smalltalk-80 language itself does not imply the meaning of those operators. The outcome of the above is only defined by how the receiver of the message (in this case a Number instance) responds to messages "+" and ">". A side effect of this mechanism is [[operator overloading]]. A message ">" can also be understood by other objects, allowing the use of expressions of the form "a > b" to compare them. ===Expressions=== Smalltalk is an [[Expression-oriented programming language|expression-based language]]. Every statement, including control constructs, has a value, which is some object. An expression can include multiple message sends. In this case expressions are parsed according to a simple order of precedence. Unary messages have the highest precedence, followed by binary messages, followed by keyword messages. For example: <syntaxhighlight lang="smalltalk">3 factorial + 4 factorial between: 10 and: 100</syntaxhighlight> is evaluated as follows: #3 receives the message "factorial" and answers 6 #4 receives the message "factorial" and answers 24 #6 receives the message "+" with 24 as the argument and answers 30 #30 receives the message "between:and:" with 10 and 100 as arguments and answers true The answer of the last message sent is the result of the entire expression. Parentheses can alter the order of evaluation when needed. For example, <syntaxhighlight lang="smalltalk">(3 factorial + 4) factorial between: 10 and: 100</syntaxhighlight> will change the meaning so that the expression first computes "3 factorial + 4" yielding 10. That 10 then receives the second "factorial" message, yielding 3628800. 3628800 then receives "between:and:", answering false. Because the meaning of binary messages is not coded into Smalltalk-80 syntax, all of them are considered to have equal precedence and are evaluated simply from left to right. Because of this, the meaning of Smalltalk expressions using binary messages can be different from their "traditional" interpretation: <syntaxhighlight lang="smalltalk">3 + 4 * 5</syntaxhighlight> is evaluated as "(3 + 4) * 5", producing 35. To obtain the expected answer of 23, parentheses must be used to explicitly define the order of operations: <syntaxhighlight lang="smalltalk">3 + (4 * 5)</syntaxhighlight> Unary messages can be ''[[method chaining|chained]]'' by writing them one after another: <syntaxhighlight lang="smalltalk">3 factorial factorial log</syntaxhighlight> which sends "factorial" to 3, then "factorial" to the result (6), then "log" to the result (720), producing the result 2.85733. A series of expressions can be written as in the following (hypothetical) example, each separated by a period (period is a statement separator, not a statement terminator). This example first creates a new instance of class Window, stores it in a variable, and then sends two messages to it. <syntaxhighlight lang="smalltalk"> | window | window := Window new. window label: 'Hello'. window open </syntaxhighlight> If a series of messages are sent to the same receiver as in the example above, they can also be written as a ''[[method cascading|cascade]]'' with individual messages separated by semicolons: <syntaxhighlight lang="smalltalk"> Window new label: 'Hello'; open </syntaxhighlight> This rewrite of the earlier example as a single expression avoids the need to store the new window in a temporary variable. According to the usual precedence rules, the unary message "new" is sent first, and then "label:" and "open" are sent to the receiver of "new". ===Code blocks=== A block of code (an anonymous function) can be expressed as a literal value (which is an object, since all values are objects). This is achieved with square brackets: <syntaxhighlight lang="smalltalk">[ :params | <message-expressions> ]</syntaxhighlight> Where '':params'' is the list of parameters the code can take. This means that the Smalltalk code: <syntaxhighlight lang="smalltalk">[:x | x + 1]</syntaxhighlight> can be understood as: :<math>f(x) = x + 1</math> or expressed in lambda terms as: :<math>\lambda x.x + 1</math> and <syntaxhighlight lang="smalltalk">[:x | x + 1] value: 3</syntaxhighlight> can be evaluated as :<math>f(3) = 3 + 1</math> Or in lambda terms as: :<math>(\lambda x. x + 1)\,3 \underset{\beta}\rightarrow 3+1</math> The resulting block object can form a [[closure (computer programming)|closure]]: it can access the variables of its enclosing lexical scopes at any time. Blocks are [[first-class object]]s. Blocks can be executed by sending them the ''value'' message. Compound variations exist to provide parameters to the block e.g., <code>value:value:</code> and <code>valueWithArguments:</code>. The literal representation of blocks was an innovation which on the one hand allowed certain code to be significantly more readable; it allowed algorithms involving iteration to be coded in a clear and concise way. Code that would typically be written with loops in some languages can be written concisely in Smalltalk using blocks, sometimes in a single line. But more importantly blocks allow control structure to be expressed using messages and [[Polymorphism (computer science)|polymorphism]], since blocks defer computation and polymorphism can be used to select alternatives. So if-then-else in Smalltalk is written and implemented as <syntaxhighlight lang="smalltalk">expr ifTrue: [statements to evaluate if expr] ifFalse: [statements to evaluate if not expr]</syntaxhighlight> ''True methods for evaluation'' {{pre|'''ifTrue:''' trueAlternativeBlock '''ifFalse:''' falseAlternativeBlock<br /> ^trueAlternativeBlock value}} ''False methods for evaluation'' {{pre|'''ifTrue:''' trueAlternativeBlock '''ifFalse:''' falseAlternativeBlock<br /> ^falseAlternativeBlock value}} <syntaxhighlight lang="smalltalk">positiveAmounts := allAmounts select: [:anAmount | anAmount isPositive]</syntaxhighlight> This is related to [[functional programming]], wherein patterns of computation (here selection) are [[Abstraction (computer science)|abstracted]] into [[higher-order function]]s. For example, the message ''select:'' on a Collection is equivalent to the higher-order function [[Filter (higher-order function)|filter]] on an appropriate [[function object|functor]].<ref>{{cite book|last1=Goldberg|first1=Adele|author-link1=Adele Goldberg (computer scientist)|last2=Robson|first2=David|year=1989|title=Smalltalk-80 The Language|publisher=Addison Wesley|isbn=0-201-13688-0|pages=17–37}}</ref>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)