GNU Smalltalk

Last updated
GNU Smalltalk
GNU Smalltalk logo.svg
Original author(s) Steve Byrne, Paolo Bonzini
Initial releaseJanuary 12, 2003;18 years ago (2003-01-12)
Stable release
3.2.5 / April 8, 2013;8 years ago (2013-04-08)
Repository
Operating system Unix (Linux, Cygwin, Mac OS X/Darwin)
Type Programming language
License GPL + LGPL
Website https://www.gnu.org/software/smalltalk/

GNU Smalltalk is an implementation of the Smalltalk programming language by the GNU Project.

Contents

The implementation, unlike other Smalltalk environments, uses text files for program input and interprets the contents as Smalltalk code. In this way, GNU Smalltalk acts more like an interpreter rather than an environment in the traditional Smalltalk manner.

GNU Smalltalk includes bindings for many free software libraries including SQLite, libSDL, cairo, gettext, and Expat.

Examples

These examples work only on GNU Smalltalk 3.0 and later versions. Classic Hello world example:

'Hello World!'displayNl

Some basic Smalltalk code:

"Everything, including a literal, is an object, so this works:"-199abs"199"'gstiscool'size"11"'Slick'indexOf:$c"4"'NiceDayIsn''tIt?'asLowercaseasSetasSortedCollectionasString"′?acdeinsty"

Collections

Constructing and using an array:

a:=#(1'hi'3.1412(45))aat:3"3.14"areverse"((4 5) 2 1 3.14 'hi' 1)"aasSet"Set(1 'hi' 3.14 2 (4 5))"

Constructing and using a hash:

hash:=Dictionaryfrom: { 'water'->'wet'.'fire'->'hot' }.hashat:'fire'"Prints:  hot"hashkeysAndValuesDo: [ :k:v|         ('%1 is %2'% { k.v }) displayNl ]  "Prints:  water is wet          fire is hot"hashremoveKey:'water'"Deletes 'water' -> 'wet'"

Blocks and iterators

Parameter-passing a block to be a closure:

"remember a block."remember:= [ :name| ('Hello, %1!'% { name }) displayNl ]."When the time is right -- call the closure!"remembervalue:'world'"=> 'Hello, world!'"

Returning closures from a method:

Integerextend [      asClosure [          | value |value:=self.^{ [ :x|value:=x ]. [ value ] }      ]  ]    blocks:=10asClosure.setter:=blocksfirst.getter:=blockssecond.gettervalue"=> 10"settervalue:21"=> 21"gettervalue"=> 21"

Using block to send info back to the caller:

Integerextend [      ifEven:evenBlockifOdd:oddBlock [          ^selfevenifTrue: [ evenBlockvalue:self ]              ifFalse: [ oddBlockvalue:self ]      ]  ] 

Invoke the above method, passing it a block:

10ifEven: [ :n|n/2 ] ifOdd: [ :n|n*3+1 ]    "=> 5"

Iterating over enumerations and arrays using blocks:

array:=#(1'hi'3.14)arraydo: [ :item|itemdisplayNl ] "=> 1""=> hi""=> 3.14"  (3to:6) do: [ :item|itemdisplayNl ] "=> 3""=> 4""=> 5""=> 6"

A method such as inject:into: can accept both a parameter and a block. It iterates over each member of a list, performing some function on while retaining an aggregate. This is analogous to the foldl function in functional programming languages. For example:

#(135)inject:10into: [ :sum:element|sum+element ] "=> 19"

On the first pass, the block receives 10 (the argument to inject) as sum, and 1 (the first element of the array) as element, This returns 11. 11 then becomes sum on the next pass, which is added to 3 to get 14. 14 is then added to 5, to finally return 19.

Blocks work with many built-in methods:

(Filename:'file.txt') withWriteStreamDo: [ :file|filenextPutAll:'Wrote some text.';nl ] "File is automatically closed here"  (Filename:'file.txt') linesDo: [ :each|eachdisplayNl ]  "=> Wrote some text."

Using an enumeration and a block to square the numbers 1 to 10:

(1to:10) collect: [ :x|xsquared ] "=> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]"

Classes

The following code defines a class named Person. By deriving from Magnitude, it automatically defines all comparison methods except one (<). With the addition of that one, asSortedCollection can sort by age. Note that we can override the way the object is printed/displayed (the default is to share the programmer-print and user-display representation) by overriding printOn:.

Magnitudesubclass:Person [     | name age |Personclass>>name:nameage:age [         ^selfnewname:name;age:age;yourself    ]      <aPerson [ ^selfage<aPersonage ]     name [ ^name ]     name:value [ name:=value ]     age [ ^age ]     age:value [ age:=value ]     printOn:aStream [ aStreamnextPutAll: ('%1 (%2)'% { name.age }) ] ]  group:= {         Personname:'Dan'age:23.Personname:'Mark'age:63.Personname:'Cod'age:16. }.  groupasSortedCollectionreverse

The above prints three names in reverse age order:

OrderedCollection (Mark (63) Dan (23) Cod (16) ) 

Exceptions

An exception is raised with a halt call:

selfhalt

An optional message can be added to the exception; there's also error: which raises a different kind of exception:

selfhalt:'This is a message'selferror:'This is a message'

These are actually wrappers for the actual exception raising method, signal:

ErrorsignalErrorsignal:'Illegal arguments!'

Exceptions are handled by on:do: blocks.

[ somethingtodo ]     on:Exceptiondo: [ :ex|handleexceptioninex ] 

Of course you can catch only particular exceptions (and their subclasses):

[ somethingtodo ]     on:Warningdo: [ :ex|handleexceptioninex ] 

It is possible to use the exception object, which is made available to the handler clause, to exit or resume the first block; exiting is the default, but can also be mentioned explicitly:

[ Errorsignal:'foo' ]     on:Errordo: [ :ex|exreturn:5 ]  (Warningsignal:'now what?') printNl"=> nil" [ (Warningsignal:'now what?')         printNl ] on:Warningdo: [ :ex|exresume:5 ]    "=> 5"

See also

Related Research Articles

Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 (S20018). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived from the ANSI Common Lisp standard.

Eiffel is an object-oriented programming language designed by Bertrand Meyer and Eiffel Software. Meyer conceived the language in 1985 with the goal of increasing the reliability of commercial software development; the first version becoming available in 1986. In 2005, Eiffel became an ISO-standardized language.

Ruby is an interpreted, high-level, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.

Smalltalk Object-oriented programming language first released in 1972

Smalltalk is an object-oriented, dynamically typed reflective programming language. Smalltalk was created as the language underpinning the "new world" of computing exemplified by "human–computer symbiosis". It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Diana Merry, Scott Wallace, and others during the 1970s.

Lua (programming language) Lightweight programming language

Lua is a lightweight, high-level, multi-paradigm programming language designed primarily for embedded use in applications. Lua is cross-platform, since the interpreter of compiled bytecode is written in ANSI C, and Lua has a relatively simple C API to embed it into applications.

GNU Octave

GNU Octave is software featuring a high-level programming language, primarily intended for numerical computations. Octave helps in solving linear and nonlinear problems numerically, and for performing other numerical experiments using a language that is mostly compatible with MATLAB. It may also be used as a batch-oriented language. Since it is part of the GNU Project, it is free software under the terms of the GNU General Public License.

Liberty BASIC

Liberty BASIC (LB) is a commercial computer programming language and integrated development environment (IDE). It has an interpreter, developed in Smalltalk, which recognizes its own dialect of the BASIC programming language. It runs on 16- and 32-bit Windows and OS/2.

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

Java syntax

The syntax of Java refers to the set of rules defining how a Java program is written and interpreted.

In computer programming, an entry point is a point in a program where the execution of a program begins, and where the program has access to command line arguments.

xHarbour is a free multi-platform extended Clipper compiler, offering multiple graphic terminals (GTs), including console drivers, GUIs, and hybrid console/GUIs. xHarbour is backward-compatible with Clipper and supports many language syntax extensions, greatly extended run-time libraries, and extensive third party support.

Magik is an object-oriented programming language that supports multiple inheritance and polymorphism, and it is dynamically typed. It was designed and implemented in 1989 by Arthur Chance of Smallworld Systems Ltd. as part of Smallworld Geographical Information System (GIS). Following Smallworld's acquisition in 2000, Magik is now provided by GE Energy, still as part of its Smallworld technology platform.

Exception handling syntax is the set of keywords and/or structures provided by a computer programming language to allow exception handling, which separates the handling of errors that arise during a program's operation from its ordinary processes. Syntax for exception handling varies between programming languages, partly to cover semantic differences but largely to fit into each language's overall syntactic structure. Some languages do not call the relevant concept "exception handling"; others may not have direct facilities for it, but can still provide means to implement it.

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted. The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.

The PHP syntax and semantics are the format (syntax) and the related meanings (semantics) of the text and symbols in the PHP programming language. They form a set of rules that define how a PHP program can be written and interpreted.

A symbol in computer programming is a primitive data type whose instances have a unique human-readable form. Symbols can be used as identifiers. In some programming languages, they are called atoms. Uniqueness is enforced by holding them in a symbol table. The most common use of symbols by programmers is for performing language reflection, and most common indirectly is their use to create object linkages.

The structure of the Perl programming language encompasses both the syntactical rules of the language and the general ways in which programs are organized. Perl's design philosophy is expressed in the commonly cited motto "there's more than one way to do it". As a multi-paradigm, dynamically typed language, Perl allows a great degree of flexibility in program design. Perl also encourages modularization; this has been attributed to the component-based design structure of its Unix roots, and is responsible for the size of the CPAN archive, a community-maintained repository of more than 100,000 modules.

Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTSTEP operating system. Objective-C was the standard programming language supported by Apple for developing macOS and iOS applications using their respective application programming interfaces (APIs), Cocoa and Cocoa Touch, until the introduction of Swift in 2014.

The syntax of the Ruby programming language is broadly similar to that of Perl and Python. Class and method definitions are signaled by keywords, whereas code blocks can be defined by either keywords or braces. In contrast to Perl, variables are not obligatorily prefixed with a sigil. When used, the sigil changes the semantics of scope of the variable. For practical purposes there is no distinction between expressions and statements. Line breaks are significant and taken as the end of a statement; a semicolon may be equivalently used. Unlike Python, indentation is not significant.