CS 342 Lecture -*- Outline -*- * Smalltalk ** Message expression syntax *** Basic expressions **** Identifiers ClassNames (start with upper case) instancevar (others start with lower case) self, super, smalltalk (pseudo variables) true, false, nil instances of True, False, UndefinedObject Case matters: True (the class) vs. true (the instance) **** Literals 3 30.45 $a "the character a" 'a string, don''t laugh!' #aSymbol #aSymbol:composed:ofKeywords: #* "also a symbol" **** Array constants #(1 2 3) #(foo bar 'and me') *** Unary messages 1 negated theta sin Pen new home *** Binary messages (always use operator characters) 3 + 4 (sum / count) * (reserve amount) *** Keyword messages (note the colons) 3 max: 2 anArray at: 2 put: 3 *** Precedence unary highest binary keyword lowest *** Associativity: left to right ------------------------ 4 - 5 * 3 (4 - 5) * 3 2 * theta sin 2 * (theta sin) frame width: otherFrame width * 2 frame width: ((otherFrame width) * 2) ------------------------ ** Blocks (closures) a procedure closure statically scoped [ i+1 ] respond to the message value, executes [ i + 1 ] value returns value of last expression [ i <- i+1. i print. i ] (separted by periods) can have arguments (x and y below) [ :x :y | (x+y) print ] responds to value:value: ** Control Structures messages sent to Booleans, Blocks, Integers, Intervals ifTrue:ifFalse:, and:, or: whileTrue:, whileFalse:, timesRepeat: do:, "following prints 1 3 5" ((1 to: 5) step: 2) do: [:i | i print] derived methods built on top of these, invent your own! collections support do:, inject:into:, collect:, select:, ... *work examples ** Classes Modules that implement abstract types (like a cluster in CLU) ------------ > Object addSubClass: #Stack instanceVariableNames: 'elems' Object > Stack display Class Name: Stack SuperClass: Object Instance Variables: elems Subclasses: Stack ------------ use addMethod to add methods to stack edit using editMethod: (set editor by editor <- 'emacs', default is 'vi') Stack addMethod --------- new elems <- List new push: anElement elems addFirst: anElement pop elems removeFirst isEmpty ^ elems isEmpty top ^ elems first printString "for Little Smalltalk, use 'contents' in ST-80" | s | s <- 'Stack ('. elems do: [ :e | s <- s , ' ', e printString]. ^ s , ' )' ------------