SlideShare a Scribd company logo
1 of 68
Stéphane Ducasse 1
Stéphane Ducasse
stephane.ducasse@inria.fr
http://stephane.ducasse.free.fr/
Syntax and Messages
S.Ducasse 2
Outline
Literals: numbers, strings, arrays....
Variable, assignments, returns
Pseudo-variables
Message Expressions
Block expressions
Conditional and Loops
S.Ducasse 3
Originally Made for Kids
Read it as a non-computer-literate person:
| bunny |
bunny := Actor fromFile:‘bunny.vrml’.
bunny head doEachFrame:
[ bunny head
pointAt: (camera
transformScreenPointToScenePoint:
(Sensor mousePoint)
using: bunny)
duration: camera rightNow ]
S.Ducasse 4
Numbers
• SmallInteger, Integer,
– 4, 2r100 (4 in base 2),3r11 (4 in base 3), 1232
• Automatic coercion
– 1 + 2.3 -> 3.3
– 1 class -> SmallInteger
– 1 class maxVal class -> SmallInteger
– (1 class maxVal + 1) class -> LargeInteger
• Fraction, Float, Double
– 3/4, 2.4e7, 0.75d
– (1/3) + (2/3) -> 1
– 1000 factorial / 999 factorial -> 1000
– 2/3 + 1 -> (5/3)
S.Ducasse 5
Characters
• Characters:
– $F, $Q $U $E $N $T $i $N
• Unprintable characters:
– Character space, Character tab, Character cr
S.Ducasse 6
Strings
• Strings:
– #mac asString -> 'mac'
– 12 printString -> '12'
– 'This packet travelled around to the printer' 'l''idiot'
– String with: $A
– Collection of characters
– ‘lulu’ at: 1 -> $l
• To introduce a single quote inside a string, just double it.
S.Ducasse 7
Symbols
• Symbols:
– #class #mac #at:put: #+ #accept:
• Kinds of String
• Unique in the system (see after)
S.Ducasse 8
Symbols vs. Strings
• Symbols are used as method selectors, unique keys for
dictionaries
• A symbol is a read-only object, strings are mutable objects
• A symbol is unique, strings are not
#calvin == #calvin PrIt-> true
‘calvin’ == ‘calvin’ PrIt-> false
#calvin, #zeBest PrIt-> 'calvinzeBest'
• Symbols are good candidates for identity based dictionaries
(IdentityDictionary)
• Hint: Comparing strings is slower then comparing symbols by a
factor of 5 to 10. However, converting a string to a symbol is
more than 100 times more expensive.
S.Ducasse 9
Comments and Tips
• "This is a comment"
• A comment can span several lines. Moreover, avoid putting a
space between the “ and the first character.When there is
no space, the system helps you to select a commented
expression.You just go after the “ character and double click
on it: the entire commented expression is selected.After
that you can printIt or doIt, etc.
S.Ducasse 10
Arrays
#(1 2 3) #('lulu' (1 2 3))
-> #('lulu' #(1 2 3))
•#(mac node1 pc node2 node3 lpr)
•an array of symbols.
•When one prints it it shows
#(#mac #node1 #pc #node2 #node3 #lpr)
•inVW Byte Array #[1 2 255]
S.Ducasse 11
Arrays
• Heterogenous
#('lulu' (1 2 3))
PrIt-> #('lulu' #(1 2 3))
#('lulu' 1.22 1)
PrIt-> #('lulu' 1.22 1)
• An array of symbols:
• #(calvin hobbes suzie)
• PrIt-> #(#calvin #hobbes #suzie)
• An array of strings:
#('calvin' 'hobbes' 'suzie')
PrIt-> #('calvin' 'hobbes' 'suzie')
S.Ducasse 12
Syntax Summary
comment: “a comment”
character: $c $h $a $r $a $c $t $e $r $s $# $@
string: ‘a nice string’ ‘lulu’ ‘l’’idiot’
symbol: #mac #+
array: #(1 2 3 (1 3) $a 4)
byte array: #[1 2 3]
integer: 1, 2r101
real: 1.5, 6.03e-34,4, 2.4e7
float: 1/33
boolean: true, false
point: 10@120
Note that @ is not an element of the syntax, but just a message sent to a
number.This is the same for /, bitShift, ifTrue:, do: ...
S.Ducasse 13
Roadmap
Literals: numbers, strings, arrays....
Variable, assignments, returns
Pseudo-variables
Message Expressions
Block expressions
Conditional and Loops
S.Ducasse 14
Variables
• Maintains a reference to an object
• Dynamically typed and can reference different types of objects
• Shared (starting with uppercase) or local/private (starting with lowercase)
S.Ducasse 15
TemporaryVariables
• To hold temporary values during evaluation (method
execution or sequence of instructions)
• Can be accessed by the expressions composing the method
body.
– | mac1 pc node1 printer mac2 packet |
S.Ducasse 16
TemporaryVariable Good Style
• Avoid using the same name for a temporary variable and a
method argument, an instance variable or another temporary
variable or block temporary.Your code will be more portable.
Do not write:
aClass>>printOn: aStream
|aStream|
...
• Instead, write:
aClass>>printOn: aStream
|anotherStream|
...
• Hint:Avoid using the same temporary variable for referencing
two different objects
S.Ducasse 17
Assignments
• An assignment is not done by message passing. It is one of
the few syntactic elements of Smalltalk.
variable := aValue
three := 3 raisedTo: 1
• Avoid using var := var2 := var3
• To not try to know in which order the expressions is
evaluated.You will write good code
S.Ducasse 18
Pointing to the Same Object
• In Smalltalk, objects are manipulated via implicit pointers:
everything is a pointer.
• Take care when different variables point to the same object:
p1 := 0@100.
p2 := p1.
p1 x: 100
p1
-> 100@100
p2
-> 100@100
S.Ducasse 19
Method Arguments
• Can be accessed by the expressions composing the method.
• Exist during the execution of the defining method.
• Method Name Example:
accept: aPacket
• In C++ or Java:
void Printer::accept(aPacket Packet)
S.Ducasse 20
Arguments are read-only
• Method arguments cannot change their value within the
method body.
• Invalid Example, assuming contents is an instance variable:
MyClass>>contents: aString
aString := aString, 'From Lpr'.
• Valid Example
MyClass>>contents: aString
| addressee |
addressee := aString , 'From Lpr'
S.Ducasse 21
Method Return
Use ^ expression to return the value of expression
from a method
Rectangle>>area
^ width * height
By default self is returned
S.Ducasse 22
InstanceVariables
• Private to a particular instance (not to all the instances of a
class like in C++).
• Can be accessed by all the methods of the defining class and
its subclasses.
• Has the same lifetime as the object.
• Declaration
Object subclass: #Node
instanceVariableNames: 'name nextNode '
...
S.Ducasse 23
InstanceVariables
• Scope: all the methods of the class
Node>>setName: aSymbol nextNode: aNode
name := aSymbol.
nextNode := aNode
• But preferably accessed using accessor methods
Node>>name
^name
S.Ducasse 24
GlobalVariables
• Always Capitalized (convention)
– MyGlobalPi := 3.1415
• If it is unknown, Smalltalk will ask you if you want to create a
new global
– Smalltalk at: #MyGlobalPi put: 3.14
– MyGlobalPi PrIt-> 3.14
– Smalltalk at: #MyGlobalPi PrIt-> 3.14
• Stored in the default environment: Smalltalk in Squeak,VW
has namespaces
• Design Hints:Accessible from everywhere, but it is not a
good idea to use them
S.Ducasse 25
Roadmap
Literals: numbers, strings, arrays....
Variable, assignments, returns
Pseudo-variables
Message Expressions
Block expressions
Conditional and Loops
S.Ducasse 26
Six Pseudo-Variables
• Smalltalk expressions can contain true, false, nil, self, super
thisContext, but cannot change their values.They are
hardwired into the compiler.
• nil nothing, the value for the uninitialized variables. Unique
instance of the class UndefinedObject
S.Ducasse 27
Six Pseudo-Variables
• true
• unique instance of the classTrue
• false
• unique instance of the class False
• Hint: Don’t use False instead of false. false is the boolean
value, False the class representing it. So, the first produces an
error, the second not:
• False ifFalse: [Transcript show:‘False’] -> error
• false ifFalse: [Transcript show:‘False’]
S.Ducasse 28
self, super, and thisContext
• Only make sense in a method body
• self refers to the receiver of a message.
• super
• refers also to the receiver of the message but its semantics
affects the lookup of the method. It starts the lookup in the
superclass of the class of the method containing the super.
• thisContext
• refers to the instance of MethodContext that represents the
context of a method (receiver, sender, method, pc, stack).
Specific toVisualWorks and to Squeak
S.Ducasse 29
self and super examples
PrinterServer>>accept: thePacket
"If the packet is addressed to me, print it.
Otherwise behave normally."
(thePacket isAddressedTo: self)
ifTrue: [self print: thePacket]
ifFalse: [super accept: thePacket]
S.Ducasse 30
thisContext Example: #haltIf:
• How supporting halt in methods that are called often (e.g.,
OrderedCollection>>add:)
• Idea: only halt if called from a method with a certain name
Object>>haltIf: aSelector
| cntxt |
cntxt := thisContext.
[cntxt sender isNil] whileFalse: [
cntxt := cntxt sender.
(cntxt selector = aSelector) ifTrue: [
Halt signal
].
].
S.Ducasse 31
Roadmap
Literals: numbers, strings, arrays....
Variable names
Pseudo-variables
Assignments, returns
Message Expressions
Block expressions
Conditional and Loops
S.Ducasse 32
Objects and Messages
• Objects communicate by sending message
• Objects react to messages by executing methods
Bot new go: 30 + 50
• A message is composed of:
• a receiver, always evaluated (Bot new)
• a selector, never evaluated #go:
• and a list possibly empty of arguments that are all evaluated
(30 + 50)
• The receiver is linked with self in a method body.
S.Ducasse 33
Three Kinds of Messages
• Unary Messages
2.4 inspect
macNode name
• Binary Messages
1 + 2 -> 3
(1 + 2) * (2 + 3) PrIt-> 15
3 * 5 PrIt-> 15
• Keyword Messages
6 gcd: 24 PrIt-> 6
pcNode nextNode: node2
Turtle new go: 30 color: Color blue
S.Ducasse 34
Unary Messages
aReceiver aSelector
node3 nextNode -> printerNode
node3 name -> #node3
1 class -> SmallInteger
false not -> true
Date today -> Date today September 19, 1997
Time now -> 1:22:20 pm
Float pi -> 3.1415926535898d
S.Ducasse 35
Binary Messages
aReceiver aSelector anArgument
•Used for arithmetic, comparison and logical operations
•One or two characters taken from:
– + - /  * ~ < > = @ % | & ! ? ,
1 + 2
2 >= 3
100@100
'the', 'best’
•Restriction:
• second character is never $-
S.Ducasse 36
Simplicity has a Price
• no mathematical precedence so take care
3 + 2 * 10 -> 50
3 + (2 * 10) -> 23
(1/3) + (2/3) and not
1/3 + 2/3
S.Ducasse 37
Keyword Messages
receiver
keyword1: argument1
keyword2: argument2
1 between: 0 and: 5
dict at: #blop put: 8+3
•In C-like languages it would be:
receiver.keyword1keyword2(argument1, argument2)
S.Ducasse 38
Keyword Messages
Workstation withName: #Mac2
mac nextNode: node1
Packet
send: 'This packet travelled around to'
to: #lw100
1@1 setX: 3
#(1 2 3) at: 2 put: 25
1 to: 10 -> (1 to: 10) anInterval
Browser newOnClass: Point
Interval from:1 to: 20 PrIt-> (1 to: 20)
12 between: 10 and: 20 PrIt-> true
x > 0 ifTrue:['positive'] ifFalse:['negative']
S.Ducasse 39
Composition Rules
• Unary-Msg > Binary-Msg > Keywords-Msg
• at same level, from the left to the right
2 + 3 squared -> 11
2 raisedTo: 3 + 2 -> 32
#(1 2 3) at: 1+1 put: 10 + 2 * 3 -> #(1 36 3)
2 raisedTo: 3 + 2 <=> (2 raisedTo: (3+2)) -> 32
S.Ducasse 40
Composition Rules
• (Msg) > Unary-Msg > Binary-Msg > Keywords-Msg
69 class inspect
(0@0 extent: 100@100) bottomRight
S.Ducasse 41
Hints ...
• Use () when two keyword-based messages occur within a
single expression, otherwise the precedence order is fine.
x isNil ifTrue: [...]
• isNil is an unary message, so it is evaluated prior to ifTrue:
x includes: 3 ifTrue: [...]
• is read as the message includes:ifTrue:
(x includes: 3) ifTrue: [...]
• We use () to disambiguate them
S.Ducasse 42
Sequence
message1 .
message2 .
message3
. is a separator, not a terminator
| macNode pcNode node1 printerNode |
macNode := Workstation withName: #mac.
Transcript cr.
Transcript show: 1 printString.
Transcript cr.
Transcript show: 2 printString
S.Ducasse 43
For the Lazy: the Cascade
receiver
selector1;
selector2; ...
•To send multiple messages to the same object
Transcript show: 1 printString.
Transcript cr
•is equivalent to:
Transcript show: 1 printString ; cr
S.Ducasse 44
Syntax Summary
assigment: var := aValue
unary message: receiver selector
binary message: receiver selector argument
keyword based: receiver keyword1: arg1 keyword2:
arg2...
cascade: message ; selector ...
separator: message . message
result: ^
parenthesis: (...)
S.Ducasse 45
Roadmap
Literals: numbers, strings, arrays....
Variable, assignments, returns
Pseudo-variables
Message Expressions
Block expressions
Conditional and Loops
S.Ducasse 46
Blocks
• anonymous methods
• deferred block of code
fct(x) = x ^ 2 + x
fct (2) = 6
fct (20) = 420
|fct|
fct:= [:x | x * x + x].
fct value: 2 PrIt-> 6
fct value: 20 PrIt-> 420
fct PrIt-> aBlockClosure
S.Ducasse 47
Blocks Continued
[ :variable1 :variable2 |
| blockTemporary1 blockTemporary2 |
expression1.
...variable1 ... ]
•Two blocks without arguments and temporary variables
PrinterServer>>accept: thePacket
(thePacket isAddressedTo: self)
ifTrue: [self print: thePacket]
ifFalse: [super accept: thePacket]
S.Ducasse 48
Block Evaluation
[....] value
or value: (for one arg)
or value:value: (for two args)
or value:value:value: …
or valueWithArguments: anArray
[2 + 3 + 4 + 5] value
[:x | x + 3 + 4 + 5 ] value: 2
[:x :y | x + y + 4 + 5] value: 2 value: 3
[:x :y :z | x + y + z + 5] value: 2 value: 3 value: 4
[:x :y :z :w | x + y + z + w] value: 2 value: 3 value: 4 value: 5
S.Ducasse 49
Block
• The value of a block is the value of its last statement, except
if there is an explicit return ^
• Blocks are first class objects.
• They are created, passed as argument, stored into variables...
S.Ducasse 50
Blocks - Continued
|index bloc |
index := 0.
bloc := [index := index +1].
index := 3.
bloc value -> 4
Integer>>factorial
"Answer the factorial of the receiver. Fail if the receiver is
less than 0."
| tmp |
....
tmp := 1.
2 to: self do: [:i | tmp := tmp * i].
^tmp
S.Ducasse 51
Literals: numbers, strings, arrays....
Variable, assignments, returns
Pseudo-variables
Message Expressions
Block expressions
Conditional and Loops
S.Ducasse 52
Yes ifTrue: is sent to a boolean
Weather isRaining
ifTrue: [self takeMyUmbrella]
ifFalse: [self takeMySunglasses]
ifTrue:ifFalse is sent to an object: a boolean!
S.Ducasse 53
Conditional: messages to booleans
• aBoolean ifTrue: aTrueBlock ifFalse: aFalseBlock
• aBoolean ifFalse: aFalseBlock ifTrue: aTrueBlock
• aBoolean ifTrue: aTrueBlock
• aBoolean ifFalse: aFalseBlock
(thePacket isAddressedTo: self)
ifTrue: [self print: thePacket]
ifFalse: [super accept: thePacket]
• Hint:Take care — true is the boolean value and True is the
class of true, its unique instance!
S.Ducasse 54
Boolean Messages
• Logical Comparisons: &, |, xor:, not
• aBooleanExpr comparison aBooleanExpr
• (1 isZero) & false
• Date today isRaining not
• Uniform, but optimized and inlined (macro expansion at
compile time)
• aBooleanExpression and: orBlock
• orBlock will only be evaluated if aBooleanExpression is
true
false and: [1 error: 'crazy']
PrIt -> false and not an error
S.Ducasse 55
Yes a collection is iterating on itself
#(1 2 -4 -86)
do: [:each | Transcript show: each abs
printString ;cr ]
> 1
> 2
> 4
> 86
Yes we ask the collection object to perform the
loop on itself
S.Ducasse 56
Some Basic Loops
• aBlockTest whileTrue
• aBlockTest whileFalse
• aBlockTest whileTrue: aBlockBody
• aBlockTest whileFalse: aBlockBody
• anInteger timesRepeat: aBlockBody
• [x<y] whileTrue: [x := x + 3]
• 10 timesRepeat: [ Transcript show: 'hello'; cr]
S.Ducasse 57
For the Curious... (VW)
BlockClosure>>whileTrue: aBlock
^ self value
ifTrue:[ aBlock value.
self whileTrue: aBlock ]
BlockClosure>>whileTrue
^ [ self value ] whileTrue:[]
S.Ducasse 58
For the Curious…
Integer>>timesRepeat: aBlock
"Evaluate the argument, aBlock, the number
of
times represented by the receiver."
| count |
count := 1.
[count <= self] whileTrue:
[aBlock value.
count := count + 1]
S.Ducasse 59
Choose your Camp!
To get all the absolute values of numbers you could
write:
|result|
aCol := #( 2 -3 4 -35 4 -11).
result := aCol species new: aCol size.
1 to: aCollection size do:
[ :each | result
at: each put: (aCol at: each) abs].
result
S.Ducasse 60
Choose your Camp!!
• You could also write:
#( 2 -3 4 -35 4 -11) collect: [ :each | each abs ]
• Really important: Contrary to the first solution, the second
solution works well for indexable collections and also for
sets.
S.Ducasse 61
Iteration Abstraction: do:/collect:
aCollection do: aOneParameterBlock
aCollection collect: aOneParameterBlock
aCollection with: anotherCollection do: aBinaryBlock
#(15 10 19 68) do:
[:i | Transcript show: i printString ; cr ]
#(15 10 19 68) collect: [:i | i odd ]
PrIt-> #(true false true false)
#(1 2 3) with: #(10 20 30)
do: [:x :y| Transcript show: (y ** x) printString ; cr ]
S.Ducasse 62
Opening the Box
Iterators are messages sent to collection objects
Collection is responsible of its traversal
SequenceableCollection>>do: aBlock
"Evaluate aBlock with each of the receiver's elements
as the argument."
1 to: self size do: [:i | aBlock value: (self at: i)]
S.Ducasse 63
select:/reject:/detect:
aCollection select: aPredicateBlock
aCollection reject: aPredicateBlock
aCollection detect: aOneParameterPredicateBlock
aCollection
detect: aOneParameterPredicateBlock
ifNone: aNoneBlock
#(15 10 19 68) select: [:i|i odd] -> (15 19)
#(15 10 19 68) reject: [:i|i odd] -> (10 68)
#(12 10 19 68 21) detect: [:i|i odd] PrIt-> 19
#(12 10 12 68) detect: [:i|i odd] ifNone:[1] PrIt-> 1
S.Ducasse 64
inject:into:
aCollection inject: aStartValue into: aBinaryBlock
| acc |
acc := 0.
#(1 2 3 4 5) do: [:element | acc := acc + element].
acc
-> 15
Is equivalent to
#(1 2 3 4 5)
inject: 0
into: [:acc :element| acc + element]
-> 15
Do not use it if the resulting code is not crystal clear!
S.Ducasse 65
Other Collection Methods
aCollection includes: anElement
aCollection size
aCollection isEmpty
aCollection contains: aBooleanBlock
#(1 2 3 4 5) includes: 4 -> true
#(1 2 3 4 5) size -> 5
#(1 2 3 4 5) isEmpty -> false
#(1 2 3 4 5) contains: [:each | each isOdd] -> true
S.Ducasse 66
[] when you don’t know times
(x isZero) ifTrue: [...]
[x<y] whileTrue: [x := x + 3]
S.Ducasse 67
What we saw
• Numbers (integer, real, float…), Character $a, String
‘abc’, Symbols (unique Strings) #jkk,
• Arrays (potentially not homogenous) #(a #(1 2 3),
Array with: 2+3
• Variables:
– Lowercase => private
– Instance variables (visible in by all methods), method
arguments (read-only), local variable |a|
– Uppercase => global
• PseudoVar: true, false, nil, self, super
– self = **always** represents the msg receiver
– nil = undefined value
S.Ducasse 68
What we saw
• Three kinds of messages
– Unary: Node new
– Binary: 1 + 2, 3@4
– Keywords: aTomagoshi eat: #cooky furiously: true
• (Msg) > unary > binary > keywords
• Same Level from left to right
• Block
– Functions
fct(x)= x*x+3, fct(2).
fct :=[:x| x * x + 3]. fct value: 2
– Anonymous method
– Passed as method argument:
factorial
tmp:= 1.
2 to: self do: [:i| tmp := tmp * i]

More Related Content

What's hot

Rust-lang
Rust-langRust-lang
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
cqtt191
 

What's hot (20)

Rust-lang
Rust-langRust-lang
Rust-lang
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
bluespec talk
bluespec talkbluespec talk
bluespec talk
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 
C++11 Multithreading - Futures
C++11 Multithreading - FuturesC++11 Multithreading - Futures
C++11 Multithreading - Futures
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
CODEsign 2015
CODEsign 2015CODEsign 2015
CODEsign 2015
 

Similar to 8 - OOP - Syntax & Messages

4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)
The World of Smalltalk
 
4 - OOP - Taste of Smalltalk (VisualWorks)
4 - OOP - Taste of Smalltalk (VisualWorks)4 - OOP - Taste of Smalltalk (VisualWorks)
4 - OOP - Taste of Smalltalk (VisualWorks)
The World of Smalltalk
 

Similar to 8 - OOP - Syntax & Messages (20)

5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)
 
4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)
 
4 - OOP - Taste of Smalltalk (VisualWorks)
4 - OOP - Taste of Smalltalk (VisualWorks)4 - OOP - Taste of Smalltalk (VisualWorks)
4 - OOP - Taste of Smalltalk (VisualWorks)
 
5 - OOP - Smalltalk in a Nutshell (b)
5 - OOP - Smalltalk in a Nutshell (b)5 - OOP - Smalltalk in a Nutshell (b)
5 - OOP - Smalltalk in a Nutshell (b)
 
4 - OOP - Taste of Smalltalk (Squeak)
4 - OOP - Taste of Smalltalk (Squeak)4 - OOP - Taste of Smalltalk (Squeak)
4 - OOP - Taste of Smalltalk (Squeak)
 
Stoop 423-smalltalk idioms
Stoop 423-smalltalk idiomsStoop 423-smalltalk idioms
Stoop 423-smalltalk idioms
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
 
Stoop 300-block optimizationinvw
Stoop 300-block optimizationinvwStoop 300-block optimizationinvw
Stoop 300-block optimizationinvw
 
#GDC15 Code Clinic
#GDC15 Code Clinic#GDC15 Code Clinic
#GDC15 Code Clinic
 
Introduction to cryptography part2-final
Introduction to cryptography  part2-finalIntroduction to cryptography  part2-final
Introduction to cryptography part2-final
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questions
 
Ruby basics ||
Ruby basics ||Ruby basics ||
Ruby basics ||
 
11 - OOP - Numbers
11 - OOP - Numbers11 - OOP - Numbers
11 - OOP - Numbers
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
 
Stoop 390-instruction stream
Stoop 390-instruction streamStoop 390-instruction stream
Stoop 390-instruction stream
 
Pharo - I have a dream @ Smalltalks Conference 2009
Pharo -  I have a dream @ Smalltalks Conference 2009Pharo -  I have a dream @ Smalltalks Conference 2009
Pharo - I have a dream @ Smalltalks Conference 2009
 
Cassandra Client Tutorial
Cassandra Client TutorialCassandra Client Tutorial
Cassandra Client Tutorial
 
Bioinformatics v2014 wim_vancriekinge
Bioinformatics v2014 wim_vancriekingeBioinformatics v2014 wim_vancriekinge
Bioinformatics v2014 wim_vancriekinge
 
EKON 12 Closures Coding
EKON 12 Closures CodingEKON 12 Closures Coding
EKON 12 Closures Coding
 

More from The World of Smalltalk (20)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
99 questions
99 questions99 questions
99 questions
 
13 traits
13 traits13 traits
13 traits
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
06 debugging
06 debugging06 debugging
06 debugging
 
05 seaside
05 seaside05 seaside
05 seaside
 
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
01 intro
01 intro01 intro
01 intro
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop metaclasses
Stoop metaclassesStoop metaclasses
Stoop metaclasses
 
Stoop ed-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 

Recently uploaded

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Recently uploaded (20)

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

8 - OOP - Syntax & Messages

  • 1. Stéphane Ducasse 1 Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Syntax and Messages
  • 2. S.Ducasse 2 Outline Literals: numbers, strings, arrays.... Variable, assignments, returns Pseudo-variables Message Expressions Block expressions Conditional and Loops
  • 3. S.Ducasse 3 Originally Made for Kids Read it as a non-computer-literate person: | bunny | bunny := Actor fromFile:‘bunny.vrml’. bunny head doEachFrame: [ bunny head pointAt: (camera transformScreenPointToScenePoint: (Sensor mousePoint) using: bunny) duration: camera rightNow ]
  • 4. S.Ducasse 4 Numbers • SmallInteger, Integer, – 4, 2r100 (4 in base 2),3r11 (4 in base 3), 1232 • Automatic coercion – 1 + 2.3 -> 3.3 – 1 class -> SmallInteger – 1 class maxVal class -> SmallInteger – (1 class maxVal + 1) class -> LargeInteger • Fraction, Float, Double – 3/4, 2.4e7, 0.75d – (1/3) + (2/3) -> 1 – 1000 factorial / 999 factorial -> 1000 – 2/3 + 1 -> (5/3)
  • 5. S.Ducasse 5 Characters • Characters: – $F, $Q $U $E $N $T $i $N • Unprintable characters: – Character space, Character tab, Character cr
  • 6. S.Ducasse 6 Strings • Strings: – #mac asString -> 'mac' – 12 printString -> '12' – 'This packet travelled around to the printer' 'l''idiot' – String with: $A – Collection of characters – ‘lulu’ at: 1 -> $l • To introduce a single quote inside a string, just double it.
  • 7. S.Ducasse 7 Symbols • Symbols: – #class #mac #at:put: #+ #accept: • Kinds of String • Unique in the system (see after)
  • 8. S.Ducasse 8 Symbols vs. Strings • Symbols are used as method selectors, unique keys for dictionaries • A symbol is a read-only object, strings are mutable objects • A symbol is unique, strings are not #calvin == #calvin PrIt-> true ‘calvin’ == ‘calvin’ PrIt-> false #calvin, #zeBest PrIt-> 'calvinzeBest' • Symbols are good candidates for identity based dictionaries (IdentityDictionary) • Hint: Comparing strings is slower then comparing symbols by a factor of 5 to 10. However, converting a string to a symbol is more than 100 times more expensive.
  • 9. S.Ducasse 9 Comments and Tips • "This is a comment" • A comment can span several lines. Moreover, avoid putting a space between the “ and the first character.When there is no space, the system helps you to select a commented expression.You just go after the “ character and double click on it: the entire commented expression is selected.After that you can printIt or doIt, etc.
  • 10. S.Ducasse 10 Arrays #(1 2 3) #('lulu' (1 2 3)) -> #('lulu' #(1 2 3)) •#(mac node1 pc node2 node3 lpr) •an array of symbols. •When one prints it it shows #(#mac #node1 #pc #node2 #node3 #lpr) •inVW Byte Array #[1 2 255]
  • 11. S.Ducasse 11 Arrays • Heterogenous #('lulu' (1 2 3)) PrIt-> #('lulu' #(1 2 3)) #('lulu' 1.22 1) PrIt-> #('lulu' 1.22 1) • An array of symbols: • #(calvin hobbes suzie) • PrIt-> #(#calvin #hobbes #suzie) • An array of strings: #('calvin' 'hobbes' 'suzie') PrIt-> #('calvin' 'hobbes' 'suzie')
  • 12. S.Ducasse 12 Syntax Summary comment: “a comment” character: $c $h $a $r $a $c $t $e $r $s $# $@ string: ‘a nice string’ ‘lulu’ ‘l’’idiot’ symbol: #mac #+ array: #(1 2 3 (1 3) $a 4) byte array: #[1 2 3] integer: 1, 2r101 real: 1.5, 6.03e-34,4, 2.4e7 float: 1/33 boolean: true, false point: 10@120 Note that @ is not an element of the syntax, but just a message sent to a number.This is the same for /, bitShift, ifTrue:, do: ...
  • 13. S.Ducasse 13 Roadmap Literals: numbers, strings, arrays.... Variable, assignments, returns Pseudo-variables Message Expressions Block expressions Conditional and Loops
  • 14. S.Ducasse 14 Variables • Maintains a reference to an object • Dynamically typed and can reference different types of objects • Shared (starting with uppercase) or local/private (starting with lowercase)
  • 15. S.Ducasse 15 TemporaryVariables • To hold temporary values during evaluation (method execution or sequence of instructions) • Can be accessed by the expressions composing the method body. – | mac1 pc node1 printer mac2 packet |
  • 16. S.Ducasse 16 TemporaryVariable Good Style • Avoid using the same name for a temporary variable and a method argument, an instance variable or another temporary variable or block temporary.Your code will be more portable. Do not write: aClass>>printOn: aStream |aStream| ... • Instead, write: aClass>>printOn: aStream |anotherStream| ... • Hint:Avoid using the same temporary variable for referencing two different objects
  • 17. S.Ducasse 17 Assignments • An assignment is not done by message passing. It is one of the few syntactic elements of Smalltalk. variable := aValue three := 3 raisedTo: 1 • Avoid using var := var2 := var3 • To not try to know in which order the expressions is evaluated.You will write good code
  • 18. S.Ducasse 18 Pointing to the Same Object • In Smalltalk, objects are manipulated via implicit pointers: everything is a pointer. • Take care when different variables point to the same object: p1 := 0@100. p2 := p1. p1 x: 100 p1 -> 100@100 p2 -> 100@100
  • 19. S.Ducasse 19 Method Arguments • Can be accessed by the expressions composing the method. • Exist during the execution of the defining method. • Method Name Example: accept: aPacket • In C++ or Java: void Printer::accept(aPacket Packet)
  • 20. S.Ducasse 20 Arguments are read-only • Method arguments cannot change their value within the method body. • Invalid Example, assuming contents is an instance variable: MyClass>>contents: aString aString := aString, 'From Lpr'. • Valid Example MyClass>>contents: aString | addressee | addressee := aString , 'From Lpr'
  • 21. S.Ducasse 21 Method Return Use ^ expression to return the value of expression from a method Rectangle>>area ^ width * height By default self is returned
  • 22. S.Ducasse 22 InstanceVariables • Private to a particular instance (not to all the instances of a class like in C++). • Can be accessed by all the methods of the defining class and its subclasses. • Has the same lifetime as the object. • Declaration Object subclass: #Node instanceVariableNames: 'name nextNode ' ...
  • 23. S.Ducasse 23 InstanceVariables • Scope: all the methods of the class Node>>setName: aSymbol nextNode: aNode name := aSymbol. nextNode := aNode • But preferably accessed using accessor methods Node>>name ^name
  • 24. S.Ducasse 24 GlobalVariables • Always Capitalized (convention) – MyGlobalPi := 3.1415 • If it is unknown, Smalltalk will ask you if you want to create a new global – Smalltalk at: #MyGlobalPi put: 3.14 – MyGlobalPi PrIt-> 3.14 – Smalltalk at: #MyGlobalPi PrIt-> 3.14 • Stored in the default environment: Smalltalk in Squeak,VW has namespaces • Design Hints:Accessible from everywhere, but it is not a good idea to use them
  • 25. S.Ducasse 25 Roadmap Literals: numbers, strings, arrays.... Variable, assignments, returns Pseudo-variables Message Expressions Block expressions Conditional and Loops
  • 26. S.Ducasse 26 Six Pseudo-Variables • Smalltalk expressions can contain true, false, nil, self, super thisContext, but cannot change their values.They are hardwired into the compiler. • nil nothing, the value for the uninitialized variables. Unique instance of the class UndefinedObject
  • 27. S.Ducasse 27 Six Pseudo-Variables • true • unique instance of the classTrue • false • unique instance of the class False • Hint: Don’t use False instead of false. false is the boolean value, False the class representing it. So, the first produces an error, the second not: • False ifFalse: [Transcript show:‘False’] -> error • false ifFalse: [Transcript show:‘False’]
  • 28. S.Ducasse 28 self, super, and thisContext • Only make sense in a method body • self refers to the receiver of a message. • super • refers also to the receiver of the message but its semantics affects the lookup of the method. It starts the lookup in the superclass of the class of the method containing the super. • thisContext • refers to the instance of MethodContext that represents the context of a method (receiver, sender, method, pc, stack). Specific toVisualWorks and to Squeak
  • 29. S.Ducasse 29 self and super examples PrinterServer>>accept: thePacket "If the packet is addressed to me, print it. Otherwise behave normally." (thePacket isAddressedTo: self) ifTrue: [self print: thePacket] ifFalse: [super accept: thePacket]
  • 30. S.Ducasse 30 thisContext Example: #haltIf: • How supporting halt in methods that are called often (e.g., OrderedCollection>>add:) • Idea: only halt if called from a method with a certain name Object>>haltIf: aSelector | cntxt | cntxt := thisContext. [cntxt sender isNil] whileFalse: [ cntxt := cntxt sender. (cntxt selector = aSelector) ifTrue: [ Halt signal ]. ].
  • 31. S.Ducasse 31 Roadmap Literals: numbers, strings, arrays.... Variable names Pseudo-variables Assignments, returns Message Expressions Block expressions Conditional and Loops
  • 32. S.Ducasse 32 Objects and Messages • Objects communicate by sending message • Objects react to messages by executing methods Bot new go: 30 + 50 • A message is composed of: • a receiver, always evaluated (Bot new) • a selector, never evaluated #go: • and a list possibly empty of arguments that are all evaluated (30 + 50) • The receiver is linked with self in a method body.
  • 33. S.Ducasse 33 Three Kinds of Messages • Unary Messages 2.4 inspect macNode name • Binary Messages 1 + 2 -> 3 (1 + 2) * (2 + 3) PrIt-> 15 3 * 5 PrIt-> 15 • Keyword Messages 6 gcd: 24 PrIt-> 6 pcNode nextNode: node2 Turtle new go: 30 color: Color blue
  • 34. S.Ducasse 34 Unary Messages aReceiver aSelector node3 nextNode -> printerNode node3 name -> #node3 1 class -> SmallInteger false not -> true Date today -> Date today September 19, 1997 Time now -> 1:22:20 pm Float pi -> 3.1415926535898d
  • 35. S.Ducasse 35 Binary Messages aReceiver aSelector anArgument •Used for arithmetic, comparison and logical operations •One or two characters taken from: – + - / * ~ < > = @ % | & ! ? , 1 + 2 2 >= 3 100@100 'the', 'best’ •Restriction: • second character is never $-
  • 36. S.Ducasse 36 Simplicity has a Price • no mathematical precedence so take care 3 + 2 * 10 -> 50 3 + (2 * 10) -> 23 (1/3) + (2/3) and not 1/3 + 2/3
  • 37. S.Ducasse 37 Keyword Messages receiver keyword1: argument1 keyword2: argument2 1 between: 0 and: 5 dict at: #blop put: 8+3 •In C-like languages it would be: receiver.keyword1keyword2(argument1, argument2)
  • 38. S.Ducasse 38 Keyword Messages Workstation withName: #Mac2 mac nextNode: node1 Packet send: 'This packet travelled around to' to: #lw100 1@1 setX: 3 #(1 2 3) at: 2 put: 25 1 to: 10 -> (1 to: 10) anInterval Browser newOnClass: Point Interval from:1 to: 20 PrIt-> (1 to: 20) 12 between: 10 and: 20 PrIt-> true x > 0 ifTrue:['positive'] ifFalse:['negative']
  • 39. S.Ducasse 39 Composition Rules • Unary-Msg > Binary-Msg > Keywords-Msg • at same level, from the left to the right 2 + 3 squared -> 11 2 raisedTo: 3 + 2 -> 32 #(1 2 3) at: 1+1 put: 10 + 2 * 3 -> #(1 36 3) 2 raisedTo: 3 + 2 <=> (2 raisedTo: (3+2)) -> 32
  • 40. S.Ducasse 40 Composition Rules • (Msg) > Unary-Msg > Binary-Msg > Keywords-Msg 69 class inspect (0@0 extent: 100@100) bottomRight
  • 41. S.Ducasse 41 Hints ... • Use () when two keyword-based messages occur within a single expression, otherwise the precedence order is fine. x isNil ifTrue: [...] • isNil is an unary message, so it is evaluated prior to ifTrue: x includes: 3 ifTrue: [...] • is read as the message includes:ifTrue: (x includes: 3) ifTrue: [...] • We use () to disambiguate them
  • 42. S.Ducasse 42 Sequence message1 . message2 . message3 . is a separator, not a terminator | macNode pcNode node1 printerNode | macNode := Workstation withName: #mac. Transcript cr. Transcript show: 1 printString. Transcript cr. Transcript show: 2 printString
  • 43. S.Ducasse 43 For the Lazy: the Cascade receiver selector1; selector2; ... •To send multiple messages to the same object Transcript show: 1 printString. Transcript cr •is equivalent to: Transcript show: 1 printString ; cr
  • 44. S.Ducasse 44 Syntax Summary assigment: var := aValue unary message: receiver selector binary message: receiver selector argument keyword based: receiver keyword1: arg1 keyword2: arg2... cascade: message ; selector ... separator: message . message result: ^ parenthesis: (...)
  • 45. S.Ducasse 45 Roadmap Literals: numbers, strings, arrays.... Variable, assignments, returns Pseudo-variables Message Expressions Block expressions Conditional and Loops
  • 46. S.Ducasse 46 Blocks • anonymous methods • deferred block of code fct(x) = x ^ 2 + x fct (2) = 6 fct (20) = 420 |fct| fct:= [:x | x * x + x]. fct value: 2 PrIt-> 6 fct value: 20 PrIt-> 420 fct PrIt-> aBlockClosure
  • 47. S.Ducasse 47 Blocks Continued [ :variable1 :variable2 | | blockTemporary1 blockTemporary2 | expression1. ...variable1 ... ] •Two blocks without arguments and temporary variables PrinterServer>>accept: thePacket (thePacket isAddressedTo: self) ifTrue: [self print: thePacket] ifFalse: [super accept: thePacket]
  • 48. S.Ducasse 48 Block Evaluation [....] value or value: (for one arg) or value:value: (for two args) or value:value:value: … or valueWithArguments: anArray [2 + 3 + 4 + 5] value [:x | x + 3 + 4 + 5 ] value: 2 [:x :y | x + y + 4 + 5] value: 2 value: 3 [:x :y :z | x + y + z + 5] value: 2 value: 3 value: 4 [:x :y :z :w | x + y + z + w] value: 2 value: 3 value: 4 value: 5
  • 49. S.Ducasse 49 Block • The value of a block is the value of its last statement, except if there is an explicit return ^ • Blocks are first class objects. • They are created, passed as argument, stored into variables...
  • 50. S.Ducasse 50 Blocks - Continued |index bloc | index := 0. bloc := [index := index +1]. index := 3. bloc value -> 4 Integer>>factorial "Answer the factorial of the receiver. Fail if the receiver is less than 0." | tmp | .... tmp := 1. 2 to: self do: [:i | tmp := tmp * i]. ^tmp
  • 51. S.Ducasse 51 Literals: numbers, strings, arrays.... Variable, assignments, returns Pseudo-variables Message Expressions Block expressions Conditional and Loops
  • 52. S.Ducasse 52 Yes ifTrue: is sent to a boolean Weather isRaining ifTrue: [self takeMyUmbrella] ifFalse: [self takeMySunglasses] ifTrue:ifFalse is sent to an object: a boolean!
  • 53. S.Ducasse 53 Conditional: messages to booleans • aBoolean ifTrue: aTrueBlock ifFalse: aFalseBlock • aBoolean ifFalse: aFalseBlock ifTrue: aTrueBlock • aBoolean ifTrue: aTrueBlock • aBoolean ifFalse: aFalseBlock (thePacket isAddressedTo: self) ifTrue: [self print: thePacket] ifFalse: [super accept: thePacket] • Hint:Take care — true is the boolean value and True is the class of true, its unique instance!
  • 54. S.Ducasse 54 Boolean Messages • Logical Comparisons: &, |, xor:, not • aBooleanExpr comparison aBooleanExpr • (1 isZero) & false • Date today isRaining not • Uniform, but optimized and inlined (macro expansion at compile time) • aBooleanExpression and: orBlock • orBlock will only be evaluated if aBooleanExpression is true false and: [1 error: 'crazy'] PrIt -> false and not an error
  • 55. S.Ducasse 55 Yes a collection is iterating on itself #(1 2 -4 -86) do: [:each | Transcript show: each abs printString ;cr ] > 1 > 2 > 4 > 86 Yes we ask the collection object to perform the loop on itself
  • 56. S.Ducasse 56 Some Basic Loops • aBlockTest whileTrue • aBlockTest whileFalse • aBlockTest whileTrue: aBlockBody • aBlockTest whileFalse: aBlockBody • anInteger timesRepeat: aBlockBody • [x<y] whileTrue: [x := x + 3] • 10 timesRepeat: [ Transcript show: 'hello'; cr]
  • 57. S.Ducasse 57 For the Curious... (VW) BlockClosure>>whileTrue: aBlock ^ self value ifTrue:[ aBlock value. self whileTrue: aBlock ] BlockClosure>>whileTrue ^ [ self value ] whileTrue:[]
  • 58. S.Ducasse 58 For the Curious… Integer>>timesRepeat: aBlock "Evaluate the argument, aBlock, the number of times represented by the receiver." | count | count := 1. [count <= self] whileTrue: [aBlock value. count := count + 1]
  • 59. S.Ducasse 59 Choose your Camp! To get all the absolute values of numbers you could write: |result| aCol := #( 2 -3 4 -35 4 -11). result := aCol species new: aCol size. 1 to: aCollection size do: [ :each | result at: each put: (aCol at: each) abs]. result
  • 60. S.Ducasse 60 Choose your Camp!! • You could also write: #( 2 -3 4 -35 4 -11) collect: [ :each | each abs ] • Really important: Contrary to the first solution, the second solution works well for indexable collections and also for sets.
  • 61. S.Ducasse 61 Iteration Abstraction: do:/collect: aCollection do: aOneParameterBlock aCollection collect: aOneParameterBlock aCollection with: anotherCollection do: aBinaryBlock #(15 10 19 68) do: [:i | Transcript show: i printString ; cr ] #(15 10 19 68) collect: [:i | i odd ] PrIt-> #(true false true false) #(1 2 3) with: #(10 20 30) do: [:x :y| Transcript show: (y ** x) printString ; cr ]
  • 62. S.Ducasse 62 Opening the Box Iterators are messages sent to collection objects Collection is responsible of its traversal SequenceableCollection>>do: aBlock "Evaluate aBlock with each of the receiver's elements as the argument." 1 to: self size do: [:i | aBlock value: (self at: i)]
  • 63. S.Ducasse 63 select:/reject:/detect: aCollection select: aPredicateBlock aCollection reject: aPredicateBlock aCollection detect: aOneParameterPredicateBlock aCollection detect: aOneParameterPredicateBlock ifNone: aNoneBlock #(15 10 19 68) select: [:i|i odd] -> (15 19) #(15 10 19 68) reject: [:i|i odd] -> (10 68) #(12 10 19 68 21) detect: [:i|i odd] PrIt-> 19 #(12 10 12 68) detect: [:i|i odd] ifNone:[1] PrIt-> 1
  • 64. S.Ducasse 64 inject:into: aCollection inject: aStartValue into: aBinaryBlock | acc | acc := 0. #(1 2 3 4 5) do: [:element | acc := acc + element]. acc -> 15 Is equivalent to #(1 2 3 4 5) inject: 0 into: [:acc :element| acc + element] -> 15 Do not use it if the resulting code is not crystal clear!
  • 65. S.Ducasse 65 Other Collection Methods aCollection includes: anElement aCollection size aCollection isEmpty aCollection contains: aBooleanBlock #(1 2 3 4 5) includes: 4 -> true #(1 2 3 4 5) size -> 5 #(1 2 3 4 5) isEmpty -> false #(1 2 3 4 5) contains: [:each | each isOdd] -> true
  • 66. S.Ducasse 66 [] when you don’t know times (x isZero) ifTrue: [...] [x<y] whileTrue: [x := x + 3]
  • 67. S.Ducasse 67 What we saw • Numbers (integer, real, float…), Character $a, String ‘abc’, Symbols (unique Strings) #jkk, • Arrays (potentially not homogenous) #(a #(1 2 3), Array with: 2+3 • Variables: – Lowercase => private – Instance variables (visible in by all methods), method arguments (read-only), local variable |a| – Uppercase => global • PseudoVar: true, false, nil, self, super – self = **always** represents the msg receiver – nil = undefined value
  • 68. S.Ducasse 68 What we saw • Three kinds of messages – Unary: Node new – Binary: 1 + 2, 3@4 – Keywords: aTomagoshi eat: #cooky furiously: true • (Msg) > unary > binary > keywords • Same Level from left to right • Block – Functions fct(x)= x*x+3, fct(2). fct :=[:x| x * x + 3]. fct value: 2 – Anonymous method – Passed as method argument: factorial tmp:= 1. 2 to: self do: [:i| tmp := tmp * i]