The Class Concept - PowerPoint PPT Presentation

About This Presentation
Title:

The Class Concept

Description:

Basic Metaphor: Data Type. NU. 4. COM3230. Dimensions of the Class Concept ... Literals (basic values) A set of operators. Operator overloading. User Defined Types ... – PowerPoint PPT presentation

Number of Views:53
Avg rating:3.0/5.0
Slides: 74
Provided by: ccs4
Category:
Tags: class | concept

less

Transcript and Presenter's Notes

Title: The Class Concept


1
The Class Concept
  • Abstraction
  • What is a class?
  • Two parts of the class
  • Two views of the class
  • Class vs. type

2
A Class -- Abstraction Over Objects
A class represents a set of objects that share a
common structure and a common behavior.
3
Class Abstraction Over Objects
  • Phenomena Similar Objects
  • Abstraction Mechanism Class
  • Basic Metaphor Data Type

An Abstraction Process
4
Dimensions of the Class Concept
  • Static vs. Dynamic Aspects
  • Shared vs. Particular features
  • Internal vs. External views
  • Multiple Interfaces
  • The Data Type Metaphor
  • Relationship with Instances
  • Class as an instance factory
  • Existence as an Object
  • Meta classes

5
What is a Class?
  • Abstraction Over Objects a set of objects that
    share
  • Dynamic Aspect
  • Protocol Declarations (signatures) of function
    members in C
  • Behavior Definitions (body) of function members
    in C
  • Static Aspect
  • Structure Declarations of data members in C.
  • But not the definitions (value) of data members.
  • State is not part of the class abstraction.
  • Mould for objects used to instantiate objects
    (instances) with distinct identities that share
    protocol, behavior and structure but may assume
    different states.
  • In contrast to concrete object, a class does not
    necessarily exist in (run) time and (memory)
    space.
  • Whats not a Class?
  • An object is not a class, but a class may be an
    object.
  • In exemplar based languages, there are no
    classes. New objects are instantiated from
    existing objects.
  • Not every set of objects is a class


6
Collaborating Classes UML
find all persons waiting at any bus stop on a bus
route
busStops
BusRoute
BusStopList
OO solution one method for each red class
buses
0..
BusStop
BusList
waiting
0..
passengers
Bus
PersonList
Static aspect Dynamic aspect
Person
0..
7
ObjectGraph in UML notation
BusList
Route1BusRoute
buses
busStops
BusStopList
Bus15Bus
passengers
CentralSquareBusStop
waiting
PersonList
PersonList
JoanPerson
PaulPerson
SeemaPerson
EricPerson
8
Shared vs. Particular Features
9
A Different Abstraction over Objects
  • Common Parts
  • Structure
  • Protocol
  • Specified per Instance
  • State values of data members.
  • Behavior values of function members.

class Stack enum N 100 int
buffN int size public void (push)(int
element) int (pop)(void)
Abstraction, but not of the desired nature!
10
The Two Views of a Class
  • Implementation the common structure and the
    details of how the behavior works.
  • Body in Ada
  • Definitions of function members in C
  • Interface the common protocol and the external
    specifications of the behavior.
  • Specification in Ada
  • Declarations in C
  • Interface as a Contract defines the contract of
    the relationship between instances of the class
    and their clients.
  • Strongly typed languages can detect some contract
    violations prior to run time.
  • Interface Components
  • Declaration of all class operations
  • Declarations of externally accessible attributes
  • Other pertinent declarations constants,
    exceptions and other classes and/or types, etc.
  • Multiple Interfaces frequently, the class has
    different interfaces to different kinds of
    clients.
  • Example electronic mail agent has different
    interfaces to users and to administrators.

11
Java Interface ClassGraphI
  • Collection getIncomingEdges(Object v) A List of
    edges (EdgeI objects) coming into node v.
  • Object getNode(String l) The node labeled l in
    the class graph.
  • Collection getNodes() A collection of nodes in
    the class graph.
  • Collection getOutgoingEdges(Object v) A
    collection of edges (EdgeI objects) going out of
    node v.

12
UML class graph
H
f
F
G
g
D
E
e
C
B
A
13
Java how to use the Interface
  • public class ClassGraph extends Object
    implements ClassGraphI

14
Java Interface EdgeI
  • String getLabel() The label of the edge, or null
    if it is not a construction edge.
  • Object getSource() The source node of the edge.
  • Object getTarget() The target node of the edge.
  • boolean isConstructionEdge() Is the edge a
    construction (part) edge?
  • boolean isInheritanceEdge() Is the edge an
    inheritance (superclass) edge?

15
Implementation in the Interface?
  • In C, the structure of an instance is defined
    in the private part of class interface.
  • Give away state information
  • Changes to representation -gt a functional affect
    on clients.
  • Why isnt the structure of an instance part of
    the Implementation?
  • Needed by the compiler.
  • Cannot allocate memory for objects without
    knowing their size.
  • Size is determined by structure.
  • Alternatives
  • OO Hardware technology is not sufficiently
    advanced.
  • Sophisticated Compilers slowly, but coming.
  • Other OOPLs not as sexy as C and Java.

16
The Two Parts of a Class
  • Dynamic Part specifications of the dynamic
    aspects of the class instances.
  • Static Part specifications of the static aspects
    of the class instances.
  • Example views and parts in Smalltalk.

Dynamic Part
Static Part
---
Instance Variables
Implementation
Interface
Messages Methods
---
17
Views and Parts in C
  • Kinds of Interfaces in C
  • Users of a Class
  • Instances
  • Subclasses
  • Clients
  • Levels of Visibility
  • private
  • protected
  • public

Dynamic Part
Static Part
private function members
private data members
public function members
public data members
18
Public Data Members?
  • class Person
  • public age int
  • class Person
  • private a int
  • public int age() return a
  • class Person
  • public int age() return current_year-birth_year
  • AVOID INTERFACE CHANGES

19
Views and Parts in Eiffel
  • Level and direction of export are orthogonal to
    kind of feature.
  • User cannot know the kind ofimplementation of a
    feature.

Dynamic Part
Static Part
Unexported routines
Unexported attributes
Exported routines
Exported without args?
20
Abstract Data Types and Classes
  • Type A set of values with common operations
  • Main Application protect mixing unrelated
    values/operations
  • Example 1 Decree forbidding pointers
    multiplication
  • Example 2 Decree against assigning a struct to
    an int variable
  • Abstract Data Type defined by the set of basic
    values, means of generating other values, set of
    allowed operations and their meaning.
  • Example Boolean type in Pascal.
  • Values True, False.
  • Operations Not, And, Or, , ltgt, lt, gt, lt, gt.
  • Implicit Operations Assignment, argument
    passing, function return value. Conversion to
    integer (ord).
  • Class A lingual mechanism that gives the means
    for realization of a
  • Type
  • Abstract Data Type
  • Abstraction

21
User Defined Types
  • If a user-defined type is to be a first class
    citizen (have the look and feel of a built-in
    type), then the programming language must provide
    the ability to define for it
  • Initialization
  • Memory management
  • Allocation
  • Deallocation
  • Type conversions
  • Literals (basic values)
  • A set of operators
  • Operator overloading

22
Inheritance
  • Sets, Objects and Inheritance
  • Specialization and Factorization
  • Basic Terminology and Notation
  • Inheritance Hierarchies

23
Inheritance -- What does it look like?
24
The Personnel Example
  • Suppose we want to computerize our personnel
    records...
  • We start by identifying the two main types of
    employees we have

struct Engineer Engineer next char
name short year_born short department int
salary char degrees void raise_salary( int
how_much ) // ...
struct SalesPerson SalesPerson next char
name short year_born short department int
salary float commission_rate void
raise_salary( int how_much ) // ...
25
Factorization and Specialization
struct Employee char name short
year_born short department int
salary Employee next void raise_salary( int
how_much ) // ...
C versionstruct Engineer struct Employee
E char degree / ... /
Indeed, inclusion is a poor mans (poor)
imitation of inheritance!
struct Engineer Employee char degrees //
...
struct SalesPerson Employee float
commission_rate // ...
26
Program Domain Example
Shape
Location Rotation
Observe the OMT (Object Modeling Technique) style
of using a triangle for denoting Inheritance
Move Locate Rotate
27
Inheritance Hierarchy
Vehicle
Observe the direction of the arrows!
Air Vehicle
Land Vehicle
Water Vehicle
Car
Truck
Airplane
Rocket
Boat
Submarine
  • Fundamental Rule
  • Suppose that a Vehicle has a
  • speed attribute, and
  • an accelerate method,
  • then all other classes in the above diagram will
    have (at least)
  • speed attribute, and
  • the same accelerate method.
  • Classification of hierarchies
  • Connected / Disconnected
  • Tree / DAG

28
Terminology Smalltalk vs. C
Smalltalk
C
Inherit Superclass Subclass Instance
Variable Method Message Class Variable Class
Method
Inherit/Derive Base class Derived class Data
Member Member function Member function
call Static data member Static function member
29
The Eiffel Terminology
  • Inheritance
  • Heir immediate subclass.
  • Descendant transitive closure of the heir
    relation.
  • Proper Descendant Descendant minus heir.
  • Parent immediate super-class.
  • Ancestor transitive closure of the parent
    relation.
  • Proper Ancestor Ancestor minus parent.
  • Taxonomy of features
  • Feature member in C.
  • Attribute data member of C.
  • Routine (Service) function member in C.
  • Procedure (Command) void function member in C
    (Mutator).
  • Function (Query) ordinary function memberin C
    (Inspector).

30
Typing and Strict Inheritance
  • Value, Type, Variable
  • Static and Dynamic Typing
  • Strict Inheritance

31
Value, Type, Variable
  • Value - the entities manipulated by programs.
  • Contents of a memory cell at a specific moment.
  • State of an object.
  • Type - means of classification of values.
  • Type is a set of values that have similar
    protocol.
  • Protocol - collection of permissible operations.
  • Variable
  • A name of a memory cell that may contain values.

32
ObjectGraph in UML notationA value
BusList
Route1BusRoute
buses
busStops
BusStopList
Bus15Bus
passengers
CentralSquareBusStop
waiting
PersonList
PersonList
JoanPerson
PaulPerson
SeemaPerson
EricPerson
33
Significance of Type
  • Type Determines Meaning What will be executed as
    a result of the following expression?
    a b
  • Integer addition, if a and b are integer, or
  • Floating point addition, if a and b are of
    floating point type, or
  • Conversion to a common type and then addition, if
    a and b are of different types.
  • Type determines whats allowed Is the following
    expression legal? Xi
  • Yes, if X of an array type and i is of an
    integral type.
  • No, e.g., if X is a real number and i is a
    function.

34
Loopholes in the Type System
  • Types usually hide the fact that a variable is
    just a box of bits, however
  • Type Casting, as in
  • long i, j, p i, q j
  • long ij ((long) p) ((long) q))
  • and union (variable records), as in
  • union
  • float f
  • long l
  • d
  • d.f 3.7
  • printf("ld\n", d.l)
  • allow one to peep into the implementation of
    types.

35
Typing in Languages
  • Formal Lang. classified by significance of type
  • Strongly typed languages a type is associated
    with each value. It is impossible to break this
    association within the framework of the language.
  • ML, Eiffel, Modula, ...
  • Weakly typed languages values have associated
    types, but it is possible for the programmer to
    break or ignore this association.
  • C, Turbo-Pascal
  • Untyped languages values have no associated
    type.
  • Assembly, BCPL, Lisp, Mathematica, Mathematical
    formulae.
  • Programming Lang. classified by time of
    enforcement
  • Dynamic typing type rules are enforced at
    run-time. Variables have no associated type.
  • Smalltalk, Prolog, ...
  • Static typing type rules are enforced at compile
    time. All variables have an associated type.
  • C, Pascal, Eiffel, ML, ...

36
Dynamic Typing
  • Type is associated with values.
  • Each value carries a tag, identifying its type.
  • A variable may contain any value of any type.

37
Strong Typing -- What does it look like?
Strong typing prevents mixing abstractions.
38
Static Typing (is Strong Typing)
  • In static typing, each variable, and even more
    generally, each identifier is associated with a
    type.
  • This usually means that all identifiers should be
    declared before used. However this is not always
    the case
  • Type inference in ML.
  • Implicit type inference in Fortran.
  • Grammatical type inference in some dialects of
    Basic.
  • A variable may contain only values of its
    associated type.
  • All expressions are guaranteed to be
    type-consistent
  • No value will be subject to operations it does
    not recognize.
  • This allows the compiler to engage in massive
    optimization.
  • Static typing goes together with strong typing
  • The two terms are used almost synonymously in the
    literature and in this course.
  • In OOP, the preferred term is strong typing,
    since, as we will see later, there is also a
    notion of dynamic type even in statically/strongly
    typed systems.

39
Why Static Typing?
  • Recursive functions theory teaches us that an
    automatic tool is very limited as a programming
    aid
  • Cannot determine if the program stops.
  • Cannot determine if the program is correct.
  • Cannot decide almost any other interesting run
    time property of a program.
  • One thing that can be done automatically is make
    sure that no run time type error occurs.
  • We can use every tiny bit of help in our struggle
    against the complexity of software!
  • Few other automatic aids are
  • Garbage collection
  • Const correctness
  • Pre and post conditions

40
Design by contract
  • Object-Oriented Software Construction by Bertrand
    Meyer, Prentice Hall
  • The presence of a precondition or postcondition
    in a routine is viewed as a contract.

41
Rights and obligations
  • Parties in the contract class and clients
  • require pre, ensure post with method r If you
    promise to call r with pre satisfied then I, in
    return, promise to deliver a final state in which
    post is satisfied.
  • Contract entails benefits and obligations for
    both parties

42
Rights and obligations
  • Precondition binds clients
  • Postcondition binds class

43
Example
44
If precondition is not satisfied
  • If clients part of the contract is not
    fulfilled, class can do what it pleases return
    any value, loop indefinitely, terminate in some
    wild way.
  • Advantage of convention simplifies significantly
    the programming style.

45
Source of complexity
  • Does data passed to a method satisfy requirement
    for correct processing?
  • Problem no checking at all or multiple
    checking.
  • Multiple checking conceptual pollution
    redundancy complicates maintenance
  • Recommended approach use preconditions

46
Class invariants and class correctness
  • Preconditions and postconditions describe
    properties of individual methods
  • Need for global properties of instances which
    must be preserved by all routines
  • 0ltnb_elements nb_elementsltmax_size
  • empty(nb_elements0)

47
Class invariants and class correctness
  • A class invariant is an assertion appearing in
    the invariant clause of the class.
  • Must be satisfied by all instances of the class
    at all stable times (instance in stable state)
  • on instance creation
  • before and after every remote call to a routine
    (may be violated during call)

48
Class invariants and class correctness
  • A class invariant only applies to public methods
    private methods are not required to maintain the
    invariant.

49
Invariant Rule
  • An assertion I is a correct class invariant for a
    class C iff the following two conditions hold
  • The constructor of C, when applied to arguments
    satisfying the constructors precondition in a
    state where the attributes have their default
    values, yields a state satisfying I.
  • Every public method of the class, when applied to
    arguments and a state satisfying both I and the
    methods precondition, yields a state satisfying
    I.

50
Invariant Rule
  • Precondition of a method may involve the initial
    state and the arguments
  • Postcondition of a method may only involve the
    final state, the initial state (through old) and
    in the case of a function, the returned value.
  • The class invariant may only involve the state

51
Invariant Rule
  • The class invariant is implicitly added (anded)
    to both the precondition and postcondition of
    every exported routine
  • Could do, in principle, without class invariants.
    But they give valuable information.
  • Class invariant acts as control on evolution of
    class
  • A class invariant applies to all contracts
    between a method of the class and a client

52
Resource Allocation
reqs
ltJobCategorygt
ltFacilitygt
0..
type
provides
0..
ltJobgt when TimeInterval
allocated
schedule
ltResourcegt
0..1
0..
inv Joballocatedltgt0 gt allocated.provides-gtincl
udesAll(type.reqs) --Any allocated resource must
have the required facilities inv Resourcejo1,
jo2 Job (schedule-gtincludesAll(jo1,jo2)
gt jo1.when.noOverlap(jo2.when) -- no
double-booking of resources
53
Benefits of Strong Typing
  • Enforce the design decisions.
  • Prevent runtime crashes
  • Mismatch in of parameters
  • Mismatch in parameters
  • Sending an object an inappropriate message
  • Early error detection reduces
  • Development time
  • Cost
  • Effort
  • Type declarations help to document programs
  • X speed ( Good )
  • Y real ( Bad )
  • Z 3 ( Worse )
  • More efficient and more compact object code
  • type SMALL_COUNTER is range 0 .. 128

54
Benefits of Strong Typing
  • class A
  • Object b
  • Object c
  • class B
  • Object d
  • class C extends B

Object
b
c
d
A
D
C
B
If all instance variables are of class Object we
get strange class graphs
55
Benefits of Strong Typing
  • class A
  • B b
  • C c
  • class B
  • D d
  • class C extends B

Object
c
A
D
b
C
B
d
56
Strict Inheritance
  • Extension of base class
  • Structure
  • Protocol
  • Behavior
  • Engineer and SalesPerson extend, each in its own
    way, the structure and protocol of Employee.
  • Identifying the Employee abstraction, helps us
    define more typesGeneral Idea similar to
    procedure call, but applied to data.
  • If procedure P calls procedure Q, then it can be
    said that P extends Q
  • P does everything that Q does more.

struct Manager public Employee char
degrees // ...
57
Is-A Relationship
  • Inheritance represents an is a relationship.
  • A subclass is a (more specialized) version of the
    base class
  • Manager is an Employee.
  • Rectangle is a Shape.
  • A function taking the class B as an argument,
    will also accept a class D derived from B.

class Monom ... Monom operator (Monom m1,
Monom m2) ... class DMonom public Monom
... d1, d2 Monom m d1 d2
58
Types and OOP
  • Types and Classes
  • Types Administrative aid
  • Check for typos.
  • Type predicates and type calculus.
  • Classes A mould for creating objects
  • Usually, type class.
  • Subtypes and Subclasses
  • Subtype a type which is a subset of another
    type.
  • Subclass a class that inherits from another
    class.
  • Extend the mould.
  • Usually, the subtype and subclass relationship
    are isomorphic.
  • Strict inheritance and Subtypes
  • With strict inheritance, we have full conformance
    and substitutability, and therefore, a subclass
    is always a subtype.

59
Properties of Strict Inheritance
  • The structure and the behavior of a subclass are
    a superset of those of the superclass.
  • The only kind of inheritance in Oberon (the
    grand-daughter of Pascal).
  • Conformance (AKA substitutability)
  • If a class B inherits from another class A, then
    the objects of B can be used wherever the objects
    of A are used.
  • Benefits of strict inheritance
  • New abstraction mechanism extend a given class
    without touching its code.
  • No performance penalty.
  • Compile-time creature.
  • Can be thought of as a syntactic sugar which
    helps define classes.
  • No conceptual penalty.
  • Structured path for understanding the classes.
  • Drawbacks of strict inheritance
  • Not overly powerful!

Except in the total size of objects, which, due
to alignment, depends on the depth of inheritance
hierarchy
60
Collections in Little Smalltalk
  • What are they?
  • Kinds of collections.
  • Basic Operations.
  • Usage of Inheritance in the Collections Library.
  • Roman numbers example.
  • The Stack Example
  • Defining a new kind of collection.

61
What are Collections?
  • Collections provide the means for managing and
    manipulating groups of objects. Kinds of
    collections
  • Set represents an unordered group of objects.
    Elements are added and removed by value.
  • Dictionary is also an unordered collection of
    elements, but insertions and removals require an
    explicit key.
  • Interval represents a sequence of numbers in
    arithmetic progression, either ascending or
    descending.
  • List is a group of objects having a specific
    linear ordering. Insertions and removals are done
    in the extremes.
  • Array a fixed-size collections. Elements can not
    be inserted or removed, but they may be
    overwritten.
  • String can be considered to be a special form of
    Array, where the elements must be characters.
  • Collections can be converted into a different
    kind by the use of messages like asSet, asArray,
    etc.

62
Classification of Collections
  • The different kinds of Collections may be
    classified according to several attributes.
  • Size
  • Fixed
  • Unbounded
  • Ordering
  • Ordered
  • Unordered
  • Access Method
  • By value
  • Indexed
  • Sequential
  • Choose the right Collection by examining its
    attributes.

63
Collections Attributes
Name Creation Fixed Order? Insertion Access R
emoval Method Size?
Method Method Method Set new no no
add includes remove Dictionary new
no no atput at
removeKey Interval n to m yes yes
none none none List new
no yes addFirst first
removeFirst
addLast remove Array new
yes yes atput at none String
new yes yes atput
at none
This is rarely a problem, since one usually
creates strings as literals.
Note however that the implementation of new in
the class String is buggy. It creates a string of
size 0!
64
Inserting an Element
  • Indexed collections (Dictionary, Array) require
    an explicit key and a value, by using the method
    atput
  • gt D lt- Dictionary new at'com1204' put'OOP' \
  • at'com3230' put'OOD' at'com3351' put'PPL'
  • Dictionary ( 'com1204' 'com3230' 'com3351' )
  • Non-indexed collections require only a value, by
    using the method add
  • gt S lt- Set new add'red' add'green' add'blue'
  • Set ( 'blue' 'green' 'red' )
  • In the case of Lists the values can be added in
    the beginning or end of the collection, by using
    the methods addFirst and addLast
  • gt L lt- List new addLast 'End' addFirst 'Begin'
  • List ( 'Begin' 'End' )

65
Removing an Element
  • In indexed collections the removal method
    requires the key.
  • gt D removeKey 'com1204'
  • Dictionary ( 'com3230' 'com3351' )
  • In collections with fixed size (Array and String)
    elements can not be removed.
  • In non-indexed collections the argument is the
    object to be removed.
  • gt S remove 'green'
  • Set ( 'blue' 'red' )
  • In a List, an element can be removed from the
    beginning (removeFirst) or by value (remove).
  • gt L removeFirst remove 'END'
  • List ( )

66
Accessing an Element
  • In indexed collections the elements are accessed
    by key.
  • gt 'SmallTalk' at 6
  • T
  • The method keys returns the keys of an indexed
    collection.
  • gt D keys
  • Set ('com3230' 'com3351')
  • In non-indexed collections we already have the
    value, hence the only question is whether it is
    in the collection.
  • gt S includes 'black'
  • false
  • The method includes is defined for all
    collections.
  • gt ( 10 20 30 40 50 ) keys includes 5
  • true

67
Selecting Elements
  • The method select returns a collection
    containing all the elements that satisfy some
    condition.
  • It receives a one-argument block that is
    evaluated for each element in the collection,
    returning true or false.
  • The returned collection is of the same class as
    the receiver in case it is Set, List, and Array,
    and Array otherwise.
  • gt ( 1 2 3 4 5 ) select i ( i rem 2 ) 0
  • Array ( 2 4 )
  • The method reject returns the complementary
    collection.
  • gt ( 1 2 3 4 5 ) asSet reject i ( i rem 2
    ) 0
  • Set ( 1 3 5 )
  • Strings are special
  • gt '1234567890' select c c gt 5
  • Array ( 6 7 8 9 )

68
Performing Computations
  • The method do allows a computation to be
    performed on every element in a collection.
  • It also receives a one-argument block.
  • gt B lt- x ( x rem 2 ) 0
  • ifTrue ( x printString , ' is even!' )
    print \
  • ifFalse ( x printString , ' is odd!' )
    print
  • Block
  • gt (1 2 3 4 5) do B
  • 1 is odd!
  • 2 is even!
  • 3 is odd!
  • 4 is even!
  • 5 is odd!
  • Array ( 1 2 3 4 5 )

69
Collecting Results
  • The method collect is similar to do, but it
    produces a new collection containing the results
    of the block evaluation for each element of the
    receiver collection.
  • gt ( 1 2 3 4 5 ) collect i i factorial
  • Array ( 1 2 6 24 120 )
  • gt ( 1 2 3 4 5 ) collect j j rem 2
  • Array ( 1 0 1 0 1 )
  • gt D lt- Dictionary new at0 put'even' at1
    put'odd'
  • Dictionary ( 'even' 'odd' )
  • gt ( 1 2 3 4 5 ) collect x D at ( x rem 2
    )
  • Array ( 'odd' 'even' 'odd' 'even' 'odd' )
  • gt factor lt- 1.1
  • 1.1
  • gt grades lt- (70 55 60 42) collect g g
    factor
  • Array ( 77 60.5 66 46.2 )

70
Accumulative Processing
  • The method injectinto is useful for processing
    all the values of a collection and returning a
    single result.
  • The first argument is the initial value, and the
    second is a two-parameter block that performs
    some computation.
  • At each iteration the block receives the result
    of the previous computation and the next value in
    the collection.
  • gt A lt- (1 2 3 4 5)
  • Array ( 1 2 3 4 5 )
  • gt ( A inject0 into a b a b ) / A size
  • 3 average of the values in the array
  • gt A inject0 into x y x gt y ifTruex
    ifFalsey
  • 5 maximum value in the array
  • gt A inject0 into i j ( j rem 2 ) 0 \
  • ifTrue i 1 ifFalse i
  • 2 number of even values in the array

71
Implementation Examples
  • Collection injectinto
  • inject aValue into aBlock last
  • last lt- aValue.
  • self do x last lt- aBlock valuelast
    valuex .
  • last
  • Collection size
  • size
  • self inject 0 into x y x 1
  • Collection occurrencesOf
  • occurrencesOf anObject
  • self inject 0
  • into x y ( y anObject )
  • ifTrue x 1
  • ifFalse x

72
Roman Numbers
  • Class Roman Object dict
  • Methods Roman 'all'
  • new
  • dict lt- Dictionary new at1 put 'I' at 4
    put 'IV'
  • at 5 put 'V' at 9 put 'IX' at 10
    put'X'
  • at 40 put 'XL' at 50 put 'L' at 90
    put 'XC'
  • at 100 put 'C' at 400 put 'CD' at 500
    put 'D'
  • at 900 put 'CM' at 1000 put 'M'
  • generate anInteger count roman
  • count lt- anInteger. roman lt- ''.
  • ( dict keys select k k lt count )
    sort reverseDo
  • key ( count quo key ) timesRepeat
  • roman lt- roman , ( dict
    at key ) .
  • count lt- count rem key .
  • roman

73
The Class Stack
  • Class Stack Object list
  • Methods Stack
  • new
  • list lt- List new
  • push anObject
  • list addFirst anObject
  • pop top
  • top lt- list first. list removeFirst. top
  • size
  • list size
  • do aBlock
  • list do aBlock

A Stack is composed by a List.
Write a Comment
User Comments (0)
About PowerShow.com