3c-1 identifiers variables literal objects numbers characters strings control structure blocks ...

23
3C-1 Identifiers Variables Literal Objects Numbers Characters Strings Control Structure Blocks Conditionals Loops Messages Defining New Classes Running Little Smalltalk A Small Example Squeak Essentials Squeak Essentials

Upload: annis-audra-sullivan

Post on 06-Jan-2018

231 views

Category:

Documents


2 download

DESCRIPTION

3C-3 Kinds of Variables Global Variables: live forever.  X := 2 Local Variables: defined in blocks/methods Live as long as needed. Often, obey call stack semantics.  Temporary Variables  Actual Parameters  Example: findSkill: aSkill | empsWithSkill | empsWithSkill := Set new. … ^empsWithSkill. Instance Variables: defined in a class definition. One copy per class instance. Live as long as the instance (also a variable) lives. Object subclass: #Color instanceVariableNames: 'rgb cachedDepth …' classVariableNames: '…'

TRANSCRIPT

Page 1: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-1

• Identifiers• Variables• Literal Objects

Numbers Characters Strings

• Control Structure Blocks Conditionals Loops

• Messages• Defining New Classes• Running Little Smalltalk• A Small Example

Squeak EssentialsSqueak Essentials

Page 2: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-2

IdentifiersIdentifiers• Variable names

Local variable: begin with a lower case letter (convention). newName := 17 Assignment

Shared variable: begin with an upper case letter (convention). Transcript Global variable

• Class names Begin with a capital letter (convention).

Integer

• Pseudo-variables: reserved names self Current object super Superclass true Instance of True false Instance of False nil Instance of UndefinedObject thisContext the top frame of the run-time stack

Method arguments Block arguments

Page 3: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-3

Kinds of VariablesKinds of Variables• Global Variables: live forever.

X := 2• Local Variables: defined in blocks/methods Live as long as

needed. Often, obey call stack semantics. Temporary Variables Actual Parameters Example: findSkill: aSkill | empsWithSkill | empsWithSkill := Set new. … ^empsWithSkill.

• Instance Variables: defined in a class definition. One copy per class instance. Live as long as the instance (also a variable) lives.Object subclass: #Color

instanceVariableNames: 'rgb cachedDepth …'classVariableNames: '…'

Page 4: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-4

Kinds of Variables – Cont.Kinds of Variables – Cont.• Class Variables: Shared among all the instances of a

class. Live as long as the class lives.Object subclass: #Color

instanceVariableNames: '…'classVariableNames: '…ColorNames…'

• Pool Variables: Shared between several classes that may not be related by inheritance.• Not a good practice – try to avoid them

ArrayedCollection subclass: #Text instanceVariableNames: 'string runs' classVariableNames: '' poolDictionaries: 'TextConstants' category: 'Collections--Text'

Page 5: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-5

Self and SuperSelf and Super• self indicates the current object itself, for

re-sending return

• super indicates the sub-object, i.e., the object corresponding to the super class. Used for Refining an overridden method:

• Example: suppose that class Manager inherits from class Employee. Then, every manager has an employee part in it:

Super

Self

Page 6: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-6

Literal ObjectsLiteral Objects• Integer

7 Uniquely identified by its name, need not be declared

• Float -3.14

• Char $A $9 $$

• StringSubclass of ArrayedCollection

'a string'

• Array #(this is an array) #(12 'abc' (another one)) {1. 2. 1+2}

• Symbol #aSymbol

Page 7: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-7

NumbersNumbers• May be Integer ( 1, -3 ), Float ( 0.25, 3.5e-2 ) or

Fraction ( 1/4, -3/5 )• Recognise arithmetic messages: + - * /• Recognise comparison messages: < > = <= >= ~=• Quotient and remainder: quo: rem:• Bitwise logical operations: bitAnd: bitInvert:

bitOr: bitXor: bitShift:• Other messages: positive, negative,

strictlyPositive, squared, sqrt, lcm:, gcd:, abs, truncated, rounded, ceiling, floor...

Page 8: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-8

CharactersCharacters• Characters are written with a preceding dollar sign.• Recognise comparison messages: < > = <= >= ~=• asInteger returns the numeric character code

corresponding to the receiver.• asString returns a string of length 1

corresponding to the receiver.• isAlphaNumeric, isDigit, isLowercase,

isUppercase return true if the receiver satisfies the condition, and false otherwise.

Page 9: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-9

StringsStrings• Are sequences of characters enclosed by single

apostrophes.• Recognise comparison messages: < > = <= >= ~=• Concatenation: ,• Change: at:put:• Substring: copyFrom:to:

Page 10: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-10

Summary: Basic ObjectsSummary: Basic ObjectsIn Smalltalk, several objects may be uniquely identified by literals. Some examples are:

Number : 1 3.14 -10 0.27e-2Character: $a $& $$String : 'Hello, world!' '9 o''clock'Array : #('cat' 'dog' 'cow') #( (1 0) (0 1) )Boolean : true falseBlock : [ :name | name print ] [ i := i + 1 ]

Other basic objects may be obtained by sending messages to these literals:

Fraction : Returned by the message / to an Integer.Examples 1/5 -2/3Interval : Returned by the message to:by: to a Number.Example 1 to:5 by:2 returns Interval( 1 3 5 )

Page 11: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-11

BlocksBlocks• A block has the general form: [arguments | statements]

Enclosed in surrounding square braces. Encapsulates a sequence of Smalltalk statements.

[ Transcript show:'hello’] Several statements are separated by dots.

[ i := i + 1 . Transcript show: i] Executes only when received a message value.

[ i := i + 1 . Transcript show: i] value May have arguments.

[ :x :y | Transcript show:(x + y)] value: 2 value: 3

Arguments are local.

• Methods are actually blocks.

Page 12: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-12

Blocks as First Class CitizensBlocks as First Class Citizens• May be stored in variables• May be returned from procedures• Example

Twice := [:x | 2 * x] Twice value: 10

20 Twice value: 5

10• Executes in the context in which it was defined.

b := [ i <- i + 1 . Transcript show: i] ...b value

The identifier i above refers to the binding known at the time the block was defined.

Capitalized Twice is acceptable, since it is a global variable.

Page 13: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-13Control StructuresControl Structures• Blocks are useful for several control structures:

anInteger timesRepeat: aBlock anArray do: aBlock anInterval do: aBlock aBoolean ifTrue: aTrueBlock ifFalse: aFalseBlock aBlock whileTrue: anotherBlock

• Examples: 5 timesRepeat:

[Transcript show: 'Hello, world!‘; cr] #(85 80 75) do: [ :grade | sum := sum + grade ] ( 0 to: 10 by: 2 ) do:

[ :i | Transcript show: i squared; cr] 0 positive ifTrue:

[Transcript show:'0 is positive‘; cr] [ count <= max ] whileTrue: [Transcript show: count;cr. count := count+1]

Page 14: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-14

Passing MessagesPassing Messages• All actions are produced by passing messages.

A message is a request for an object to perform some operation.

A message can contain certain argument values.

• The behaviour of an object in response to a specific message is dictated by the object’s class. An object is an instance of a larger class (category) of

objects.

• The list of statements that define how an instance of some class will respond to a message is called the method for that message.

Page 15: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-15

Message TypesMessage TypesMessages have the general form:

receiver selector arguments

• Unary messages Formed by a single word, requires no arguments.

•7 sign Yields 1•7 factorial sqrt Evaluated from left to right: sqrt(7!)

• Binary messages Formed from one or two adjacent nonalphabetic characters, a

single argument is required. •7 + 4 Yields 11•7 + 4 * 3 Yields 33•7 + 17 sqrt Unary message has a higher precedence

• Keyword messages Consists of one or more keywords (an identifier followed by a

colon), each keyword requires an argument.•7 max: 14•7 between: 2 sqrt and: 4 + 2

Page 16: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-16

MessagesMessages’’ Precedence Precedence• Unary messages have precedence over binary

messages, that have precedence over keyword messages.

> 4 squared + 1 negated gcd: 3 factorial3• Parentheses may be used to change precedence.> ( 4 squared + 1 negated gcd: 3 ) factorial6• Keyword messages can not be combined.> 100 quo: 5 rem: 3ERROR: SmallInteger does not understand message #quo:rem:

• Keyword messages can be separated by parentheses.> ( 100 quo: 5 ) rem: 32

Page 17: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-17

CascadesCascades• The character ; may be used to send several

messages to the same object.• The receiver of all cascaded messages is the receiver

of the first message involved in a cascade• The value returned by a cascade of messages is the

value of the last cascaded messageExamples:> 2+2; * 1000; squared; factorial; sqrt 1.414213562373095 > ( 'Smalltalk' copyFrom:1 to:5 ) size5> 'Smalltalk' copyFrom:1 to:5; size9> 'Smalltalk' at:4 put:$r; at:5 put:$t;asStringSmarttalk Why wasn’t the answer Smarltalk ?!?

Page 18: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-18

Defining the Class Point2DDefining the Class Point2D* File point2D.st

Object subclass: #Point2DinstanceVariableNames: 'xCoord yCoord’classVariableNames: ‘’poolDictionaries: ‘’category: 'Point'!

initialize xCoord := 0. yCoord := 0

! ! x: newX

xCoord := newX! !

y: newYyCoord := newY

! !x: newX y: newYself x: newX. self y: newY

! !

Page 19: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-19

The Class Point2D (cont.)The Class Point2D (cont.)x^xCoord

! !

y^yCoord

! !

distanceTo: aPoint^ ( ( xCoord - aPoint x ) squared +( yCoord - aPoint y ) squared ) sqrt

! !

printString^'( ', xCoord printString, ' , ',yCoord printString, ' )'

Page 20: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-20

Using the Class Point2DUsing the Class Point2D> (Point2D methodDict keys) do:

[:x | Transcript show: x asString; show: ‘ ’]distanceTo: initialize y x: printString x:y: y:

x> origin := Point2D new( 0 , 0 )> aPoint := Point2D new.> aPoint x: 3; y: 4( 3 , 4 )> aPoint x + aPoint y7> aPoint distanceTo: origin5.0

Page 21: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-21

Manipulating a PointManipulating a Point• p := Point new

Assigns to p an object of class Point

• p x: 3 y: 4 Sends the point object p a keyword message x:y:

• p x Sends the point object p an unary message x The object returns as a result the object 3

• p rho Sends the point object p an unary message rho The object returns as a result the object 5 Oops, but rho is not defined yet...

Page 22: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-22

Adding Methods to Class Point2DAdding Methods to Class Point2D

rho: dist theta: angle xCoord := dist * angle cos. yCoord := dist * angle sin! ! rho ^ (xCoord squared + yCoord squared) sqrt! ! theta

^ (yCoord / xCoord) arcTan

Page 23: 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes

3C-23

Summary of Main PointsSummary of Main Points• Objects

Everything is an object. Each object is an instance of a class. Instance variables are private.

• Messages All actions are produced by passing messages. A message activates a method.

• Methods A method has a signature (selector & arguments) that

defines how it is to be used. ^exp returns the value of exp (an object) as the

result.