SlideShare a Scribd company logo
1 of 10
10.1 Packaging procedures and state
Recall our counter from Example 9.1
(define (update-counter!) (set! counter (+ counter 1)) counter)
Every time an application of update-counter! is evaluated, we expect to obtain a value one
larger than the previous application.
This only works, however, if there are no other evaluations that modify
the counter variable.
Hence, we can only have one counter: there is only one counter place in the global
environment.
If we want to have a second counter, we would need to define a new variable
(such as counter2, and implement a new procedure, update-counter2!,
that is identical to update-counter!, but manipulates counter2instead. For each
new counter, we would need a new variable and a new procedure.
10.1.1 Encapsulation
It would be more useful to package the counter variable with the procedure that
manipulates it.
Then we could create as many counters as we want, each with its own counter variable
to manipulate.
The Stateful Application Rule (from Section 9.2.2) suggests a way to do this: evaluating
an application creates a new environment, so a counter variable defined an the
application environment is only visible through body of the created procedure.
The make-counter procedure creates a counter object that packages the countvariable
with the procedure that increases its value:
(define (make-counter) ((lambda (count)
(lambda () (set! count (+ 1 count)) count))
0))
Each application of make-counter produces a new object that is a procedure with its own
associated count variable.
Protecting state so it can only be manipulated in controlled ways is known
as encapsulation.
The count place is encapsulated within the counter object.
Whereas the previous counter used the global environment to store the counter in a way
that could be manipulated by other expressions, this version encapsulates the counter
variable so the only way to manipulate the counter value is through the counter object.
An equivalent make-counter definition uses a let expression to make the initialization of
the count variable clearer:
(define (make-counter) (let ((count 0))
(lambda () (set! count (+ 1 count)) count)))
Figure 10.1 depicts the environment after creating two counter objects and applying one
of them.
Figure 10.1: Environment produced by evaluating.
10.1.2 Messages
The object produced by make-counter is limited to only one behavior: every time it
is applied the associated count variable is increased by one and the new value is output.
To produce more useful objects, we need a way to combine state with multiple
behaviors.
For example, we might want a counter that can also return the current count and reset
the count. We do this by adding a message parameter to the procedure produced
by make-counter:
(define (make-counter)
(let ((count 0))
(lambda (message)
'get-count) count
'reset!) (set! count 0)
(if (eq? message
(if (eq? message 'next!) (set!
count (+ 1 count))(if (eq? message
(error "Unrecognized message")))))))
Like the earlier make-counter, this procedure produces a procedure with an environment
containing a frame with a place named count.
The produced procedure takes a message parameter and selects different
behavior depending on the input message.
The message parameter is a Symbol. A Symbol is a sequence of characters preceded by a
quote character such as 'next!.
Two Symbols are equal, as determined by the eq? procedure, if their sequences of
characters are identical.
The running time of the eq? procedure on symbol type inputs is constant; it does
not increase with the length of the symbols since the symbols can be represented
internally as small numbers and compared quickly using number equality.
This makes symbols a more efficient way of selecting object behaviors than Strings, and
a more memorable way to select behaviors than using Numbers.
Here are some sample interactions using the counter object:
> (define counter (make-counter))
> (counter
> (counter 1
> (counter Unrecognized message
'next!)
'get-count)
'previous!)
Conditional expressions. For objects with many behaviors, the nested if expressions
can get quite cumbersome. Scheme provides a compact conditional expression for
combining many if expressions into one smaller expression:
The evaluation rule for a conditional expression can be defined as a transformation into
an if expression: Evaluation Rule 9: Conditional. The conditional
expression (cond) has no value.
All other conditional expressions are of the form (cond
(Expressionp1Expressionp1 Expressionc1Expressionc1) Rest) where Rest is a list of
conditional clauses. The value of such a conditional expression is the value of the
if expression:
(if Expressionp1Expressionp1 Expressionc1Expressionc1 (cond Rest))
This evaluation rule is recursive since the transformed expression still includes a
conditional expression, but uses the empty conditional with no value as its base case.
The conditional expression can be used to define make-counter more clearly than
the nested if expressions:
(define (make-counter) (let ((count 0))
(lambda (message)
'get-count) count)
(set! count 0))
(cond ((eq? message
((eq? message 'reset!)
((eq? message 'next!) (set! count (+ 1 count))) (true (error
"Unrecognized message"))))))
For linguistic convenience, Scheme provides a special syntax else
for use in conditional expressions.
When used as the predicate in the last conditional clause it means the same
thing as true. So, we could write the last clause equivalently as (else (error
"Unrecognized message")).
Sending messages. A more natural way to interact with objects is to define a generic
procedure that takes an object and a message as its parameters, and send the message to
the object.
The ask procedure is a simple procedure that does this:
(define (ask object message) (object message))
It applies the object input to the message input. So, (ask counter 'next!) is equivalent
to (counter 'next!), but looks more like passing a message to an object than
applying a procedure.
Later, we will develop more complex versions of the ask procedure to provide a
more powerful object model.
Messages with parameters. Sometimes it is useful to have behaviors that take
additional parameters. For example, we may want to support a message adjust!that
increases the counter value by an input value.
To support such behaviors, we generalize the behaviors so that the result of applying the
message dispatching procedure is itself a procedure.
The procedures for reset!, next!, and get-count take no parameters; the procedure
for adjust! takes one parameter.
(define (make-adjustable-counter)
(let ((count 0))
(lambda (message)
'get-count) (lambda () count))
'reset!) (lambda () (set! count 0)))
(cond ((eq? message
((eq? message
((eq? message 'next!) (lambda () (set! count (+ 1 count))))
((eq? message (lambda (val) (set! count (+ count 'adjust!)
val))))
(else (error "Unrecognized message"))))))
We also need to also change the ask procedure to pass in the extra arguments. So
far, all the procedures we have defined take a fixed number of operands.
To allow ask to work for procedures that take a variable number of arguments, we use a
special definition construct:
The name following the dot is bound to all the remaining operands combined into a list.
This means the defined procedure can be applied to nn or more operands where nn is
the number of names in Parameters.
If there are only nnoperand expressions, the value bound to NameRestRest is null.
If there are n+kn+koperand expressions, the value bound to NameRestRest is a
list containing the values of the last kk operand expressions.
To apply the procedure we use the built-in apply procedure which takes two
inputs, a Procedure and a List.
It applies the procedure to the values in the list, extracting them from the list as each
operand in order.
(define (ask object message . args) (apply (object message) args))
We can use the new ask procedure with two or more parameters to invoke methods with
any number of arguments (e.g., > (ask counter 'adjust! 5)).
10.1.3 Object Terminology
An object is an entity that packages state and procedures.
The state variables that are part of an object are called instance variables. The instance
variables are stored in places that are part of the application environment for the object.
This means they are encapsulated with the object and can only be accessed through the
object. An object produced by (make-counter) defines a single instance variable, count.
The procedures that are part of an object are called methods. Methods may
provide information about the state of an object (we call these observers) or modify the
state of an object (we call these mutators).
An object produced by(make-counter) provides three methods: reset! (a mutator), next! (a
mutator), and get-count (an observer).
An object is manipulated using the object's methods. We invoke a method on an object
by sending the object a message. This is analogous to applying a procedure.
A class is a kind of object. Classes are similar to data types. They define a set of possible
values and operations (methods in the object terminology) for manipulating those
values.
We also need procedures for creating new objects, such as the make-
counterprocedure above. We call these constructors.
By convention, we call the constructor for a class make- where `` is the name of
the class. Hence, an instance of the counter class is the result produced when the
make- counterprocedure is applied.

More Related Content

What's hot

Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector classNontawat Wongnuk
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
Chapter 6.3
Chapter 6.3Chapter 6.3
Chapter 6.3sotlsoc
 
Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentationguest0d6229
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.comDavisMurphyB81
 
What is new on ES6
What is new on ES6What is new on ES6
What is new on ES6Huge
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
E2D3 ver. 0.2 API Instruction
E2D3 ver. 0.2 API InstructionE2D3 ver. 0.2 API Instruction
E2D3 ver. 0.2 API InstructionE2D3.org
 
ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com donaldzs157
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Basics of dictionary object
Basics of dictionary objectBasics of dictionary object
Basics of dictionary objectNilanjan Saha
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaEduardo Bergavera
 
Creating a Custom Tanimoto or Cosine Similarity Vector Operator for Lucene / ...
Creating a Custom Tanimoto or Cosine Similarity Vector Operator for Lucene / ...Creating a Custom Tanimoto or Cosine Similarity Vector Operator for Lucene / ...
Creating a Custom Tanimoto or Cosine Similarity Vector Operator for Lucene / ...Lucidworks
 
Chain of Responsibility Pattern
Chain of Responsibility PatternChain of Responsibility Pattern
Chain of Responsibility PatternHüseyin Ergin
 

What's hot (20)

Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector class
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
inheritance
inheritanceinheritance
inheritance
 
Arrays
ArraysArrays
Arrays
 
Chapter 6.3
Chapter 6.3Chapter 6.3
Chapter 6.3
 
Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentation
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.com
 
What is new on ES6
What is new on ES6What is new on ES6
What is new on ES6
 
Scala oo (1)
Scala oo (1)Scala oo (1)
Scala oo (1)
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
What Do You Mean By NUnit
What Do You Mean By NUnitWhat Do You Mean By NUnit
What Do You Mean By NUnit
 
E2D3 ver. 0.2 API Instruction
E2D3 ver. 0.2 API InstructionE2D3 ver. 0.2 API Instruction
E2D3 ver. 0.2 API Instruction
 
ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Basics of dictionary object
Basics of dictionary objectBasics of dictionary object
Basics of dictionary object
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Creating a Custom Tanimoto or Cosine Similarity Vector Operator for Lucene / ...
Creating a Custom Tanimoto or Cosine Similarity Vector Operator for Lucene / ...Creating a Custom Tanimoto or Cosine Similarity Vector Operator for Lucene / ...
Creating a Custom Tanimoto or Cosine Similarity Vector Operator for Lucene / ...
 
Chain of Responsibility Pattern
Chain of Responsibility PatternChain of Responsibility Pattern
Chain of Responsibility Pattern
 

Viewers also liked

Inference rulesproofmethods
Inference rulesproofmethodsInference rulesproofmethods
Inference rulesproofmethodsRajendran
 
object oriented-programming
object oriented-programmingobject oriented-programming
object oriented-programmingRajendran
 
evaluation rules
evaluation rulesevaluation rules
evaluation rulesRajendran
 
best first-sort
best first-sortbest first-sort
best first-sortRajendran
 
language construction
language constructionlanguage construction
language constructionRajendran
 
composing procedures
composing procedurescomposing procedures
composing proceduresRajendran
 
Introduction to trees
Introduction to treesIntroduction to trees
Introduction to treesRajendran
 
1.2 steps and functionalities
1.2 steps and functionalities1.2 steps and functionalities
1.2 steps and functionalitiesRajendran
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional arrayRajendran
 
Chomsky & Greibach Normal Forms
Chomsky & Greibach Normal FormsChomsky & Greibach Normal Forms
Chomsky & Greibach Normal FormsRajendran
 
Variants of Turing Machine
Variants of Turing MachineVariants of Turing Machine
Variants of Turing MachineRajendran
 
Partial compute function
Partial compute functionPartial compute function
Partial compute functionRajendran
 

Viewers also liked (18)

Inference rulesproofmethods
Inference rulesproofmethodsInference rulesproofmethods
Inference rulesproofmethods
 
scheme
scheme scheme
scheme
 
object oriented-programming
object oriented-programmingobject oriented-programming
object oriented-programming
 
evaluation rules
evaluation rulesevaluation rules
evaluation rules
 
best first-sort
best first-sortbest first-sort
best first-sort
 
universality
universalityuniversality
universality
 
language construction
language constructionlanguage construction
language construction
 
Array1
Array1Array1
Array1
 
composing procedures
composing procedurescomposing procedures
composing procedures
 
Tree basics
Tree basicsTree basics
Tree basics
 
Introduction to trees
Introduction to treesIntroduction to trees
Introduction to trees
 
1.2 steps and functionalities
1.2 steps and functionalities1.2 steps and functionalities
1.2 steps and functionalities
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Chomsky & Greibach Normal Forms
Chomsky & Greibach Normal FormsChomsky & Greibach Normal Forms
Chomsky & Greibach Normal Forms
 
Variants of Turing Machine
Variants of Turing MachineVariants of Turing Machine
Variants of Turing Machine
 
Shell sort
Shell sortShell sort
Shell sort
 
Partial compute function
Partial compute functionPartial compute function
Partial compute function
 
Ambiguty
AmbigutyAmbiguty
Ambiguty
 

Similar to Create Multiple Counters Using Object Encapsulation

Bt0082 visual basic2
Bt0082 visual basic2Bt0082 visual basic2
Bt0082 visual basic2Techglyphs
 
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Philip Schwarz
 
Transaction Management, Recovery and Query Processing.pptx
Transaction Management, Recovery and Query Processing.pptxTransaction Management, Recovery and Query Processing.pptx
Transaction Management, Recovery and Query Processing.pptxRoshni814224
 
Parameter Estimation User Guide
Parameter Estimation User GuideParameter Estimation User Guide
Parameter Estimation User GuideAndy Salmon
 
CFM Challenge - Course Project
CFM Challenge - Course ProjectCFM Challenge - Course Project
CFM Challenge - Course ProjectKhalilBergaoui
 
SBSI optimization tutorial
SBSI optimization tutorialSBSI optimization tutorial
SBSI optimization tutorialRichard Adams
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2dplunkett
 
impact of_mutation
impact of_mutationimpact of_mutation
impact of_mutationRajendran
 
Paca java script slid
Paca java script slidPaca java script slid
Paca java script slidpacatarpit
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1Vahid Farahmandian
 
Technologies used in the PVS-Studio code analyzer for finding bugs and potent...
Technologies used in the PVS-Studio code analyzer for finding bugs and potent...Technologies used in the PVS-Studio code analyzer for finding bugs and potent...
Technologies used in the PVS-Studio code analyzer for finding bugs and potent...Andrey Karpov
 

Similar to Create Multiple Counters Using Object Encapsulation (20)

Vbscript
VbscriptVbscript
Vbscript
 
VB Script
VB ScriptVB Script
VB Script
 
Sharbani bhattacharya VB Structures
Sharbani bhattacharya VB StructuresSharbani bhattacharya VB Structures
Sharbani bhattacharya VB Structures
 
Bt0082 visual basic2
Bt0082 visual basic2Bt0082 visual basic2
Bt0082 visual basic2
 
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
 
Transaction Management, Recovery and Query Processing.pptx
Transaction Management, Recovery and Query Processing.pptxTransaction Management, Recovery and Query Processing.pptx
Transaction Management, Recovery and Query Processing.pptx
 
Parameter Estimation User Guide
Parameter Estimation User GuideParameter Estimation User Guide
Parameter Estimation User Guide
 
CFM Challenge - Course Project
CFM Challenge - Course ProjectCFM Challenge - Course Project
CFM Challenge - Course Project
 
SBSI optimization tutorial
SBSI optimization tutorialSBSI optimization tutorial
SBSI optimization tutorial
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
impact of_mutation
impact of_mutationimpact of_mutation
impact of_mutation
 
Paca java script slid
Paca java script slidPaca java script slid
Paca java script slid
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Maxbox starter
Maxbox starterMaxbox starter
Maxbox starter
 
Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1
 
Vb script final pari
Vb script final pariVb script final pari
Vb script final pari
 
Copy on write
Copy on writeCopy on write
Copy on write
 
Technologies used in the PVS-Studio code analyzer for finding bugs and potent...
Technologies used in the PVS-Studio code analyzer for finding bugs and potent...Technologies used in the PVS-Studio code analyzer for finding bugs and potent...
Technologies used in the PVS-Studio code analyzer for finding bugs and potent...
 
Notes on c++
Notes on c++Notes on c++
Notes on c++
 

More from Rajendran

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower boundsRajendran
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsRajendran
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower boundsRajendran
 
Red black tree
Red black treeRed black tree
Red black treeRajendran
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statisticsRajendran
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theoremRajendran
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree methodRajendran
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theoremRajendran
 
Master method
Master method Master method
Master method Rajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithmsRajendran
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisRajendran
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisRajendran
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of QuicksortRajendran
 
Np completeness
Np completenessNp completeness
Np completenessRajendran
 
computer languages
computer languagescomputer languages
computer languagesRajendran
 

More from Rajendran (20)

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower bounds
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding Costs
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower bounds
 
Red black tree
Red black treeRed black tree
Red black tree
 
Hash table
Hash tableHash table
Hash table
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statistics
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theorem
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theorem
 
Master method
Master method Master method
Master method
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Hash tables
Hash tablesHash tables
Hash tables
 
Lower bound
Lower boundLower bound
Lower bound
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm Analysis
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of Quicksort
 
Np completeness
Np completenessNp completeness
Np completeness
 
computer languages
computer languagescomputer languages
computer languages
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 

Create Multiple Counters Using Object Encapsulation

  • 1. 10.1 Packaging procedures and state Recall our counter from Example 9.1 (define (update-counter!) (set! counter (+ counter 1)) counter) Every time an application of update-counter! is evaluated, we expect to obtain a value one larger than the previous application. This only works, however, if there are no other evaluations that modify the counter variable. Hence, we can only have one counter: there is only one counter place in the global environment. If we want to have a second counter, we would need to define a new variable (such as counter2, and implement a new procedure, update-counter2!, that is identical to update-counter!, but manipulates counter2instead. For each new counter, we would need a new variable and a new procedure.
  • 2. 10.1.1 Encapsulation It would be more useful to package the counter variable with the procedure that manipulates it. Then we could create as many counters as we want, each with its own counter variable to manipulate. The Stateful Application Rule (from Section 9.2.2) suggests a way to do this: evaluating an application creates a new environment, so a counter variable defined an the application environment is only visible through body of the created procedure. The make-counter procedure creates a counter object that packages the countvariable with the procedure that increases its value: (define (make-counter) ((lambda (count) (lambda () (set! count (+ 1 count)) count)) 0)) Each application of make-counter produces a new object that is a procedure with its own associated count variable. Protecting state so it can only be manipulated in controlled ways is known as encapsulation. The count place is encapsulated within the counter object. Whereas the previous counter used the global environment to store the counter in a way that could be manipulated by other expressions, this version encapsulates the counter variable so the only way to manipulate the counter value is through the counter object.
  • 3. An equivalent make-counter definition uses a let expression to make the initialization of the count variable clearer: (define (make-counter) (let ((count 0)) (lambda () (set! count (+ 1 count)) count))) Figure 10.1 depicts the environment after creating two counter objects and applying one of them. Figure 10.1: Environment produced by evaluating.
  • 4. 10.1.2 Messages The object produced by make-counter is limited to only one behavior: every time it is applied the associated count variable is increased by one and the new value is output. To produce more useful objects, we need a way to combine state with multiple behaviors. For example, we might want a counter that can also return the current count and reset the count. We do this by adding a message parameter to the procedure produced by make-counter: (define (make-counter) (let ((count 0)) (lambda (message) 'get-count) count 'reset!) (set! count 0) (if (eq? message (if (eq? message 'next!) (set! count (+ 1 count))(if (eq? message (error "Unrecognized message"))))))) Like the earlier make-counter, this procedure produces a procedure with an environment containing a frame with a place named count. The produced procedure takes a message parameter and selects different behavior depending on the input message. The message parameter is a Symbol. A Symbol is a sequence of characters preceded by a quote character such as 'next!.
  • 5. Two Symbols are equal, as determined by the eq? procedure, if their sequences of characters are identical. The running time of the eq? procedure on symbol type inputs is constant; it does not increase with the length of the symbols since the symbols can be represented internally as small numbers and compared quickly using number equality. This makes symbols a more efficient way of selecting object behaviors than Strings, and a more memorable way to select behaviors than using Numbers. Here are some sample interactions using the counter object: > (define counter (make-counter)) > (counter > (counter 1 > (counter Unrecognized message 'next!) 'get-count) 'previous!) Conditional expressions. For objects with many behaviors, the nested if expressions can get quite cumbersome. Scheme provides a compact conditional expression for combining many if expressions into one smaller expression:
  • 6. The evaluation rule for a conditional expression can be defined as a transformation into an if expression: Evaluation Rule 9: Conditional. The conditional expression (cond) has no value. All other conditional expressions are of the form (cond (Expressionp1Expressionp1 Expressionc1Expressionc1) Rest) where Rest is a list of conditional clauses. The value of such a conditional expression is the value of the if expression: (if Expressionp1Expressionp1 Expressionc1Expressionc1 (cond Rest)) This evaluation rule is recursive since the transformed expression still includes a conditional expression, but uses the empty conditional with no value as its base case. The conditional expression can be used to define make-counter more clearly than the nested if expressions: (define (make-counter) (let ((count 0)) (lambda (message) 'get-count) count) (set! count 0)) (cond ((eq? message ((eq? message 'reset!) ((eq? message 'next!) (set! count (+ 1 count))) (true (error "Unrecognized message")))))) For linguistic convenience, Scheme provides a special syntax else for use in conditional expressions. When used as the predicate in the last conditional clause it means the same thing as true. So, we could write the last clause equivalently as (else (error "Unrecognized message")).
  • 7. Sending messages. A more natural way to interact with objects is to define a generic procedure that takes an object and a message as its parameters, and send the message to the object. The ask procedure is a simple procedure that does this: (define (ask object message) (object message)) It applies the object input to the message input. So, (ask counter 'next!) is equivalent to (counter 'next!), but looks more like passing a message to an object than applying a procedure. Later, we will develop more complex versions of the ask procedure to provide a more powerful object model. Messages with parameters. Sometimes it is useful to have behaviors that take additional parameters. For example, we may want to support a message adjust!that increases the counter value by an input value. To support such behaviors, we generalize the behaviors so that the result of applying the message dispatching procedure is itself a procedure. The procedures for reset!, next!, and get-count take no parameters; the procedure for adjust! takes one parameter.
  • 8. (define (make-adjustable-counter) (let ((count 0)) (lambda (message) 'get-count) (lambda () count)) 'reset!) (lambda () (set! count 0))) (cond ((eq? message ((eq? message ((eq? message 'next!) (lambda () (set! count (+ 1 count)))) ((eq? message (lambda (val) (set! count (+ count 'adjust!) val)))) (else (error "Unrecognized message")))))) We also need to also change the ask procedure to pass in the extra arguments. So far, all the procedures we have defined take a fixed number of operands. To allow ask to work for procedures that take a variable number of arguments, we use a special definition construct: The name following the dot is bound to all the remaining operands combined into a list. This means the defined procedure can be applied to nn or more operands where nn is the number of names in Parameters. If there are only nnoperand expressions, the value bound to NameRestRest is null. If there are n+kn+koperand expressions, the value bound to NameRestRest is a list containing the values of the last kk operand expressions. To apply the procedure we use the built-in apply procedure which takes two inputs, a Procedure and a List. It applies the procedure to the values in the list, extracting them from the list as each operand in order. (define (ask object message . args) (apply (object message) args))
  • 9. We can use the new ask procedure with two or more parameters to invoke methods with any number of arguments (e.g., > (ask counter 'adjust! 5)). 10.1.3 Object Terminology An object is an entity that packages state and procedures. The state variables that are part of an object are called instance variables. The instance variables are stored in places that are part of the application environment for the object. This means they are encapsulated with the object and can only be accessed through the object. An object produced by (make-counter) defines a single instance variable, count. The procedures that are part of an object are called methods. Methods may provide information about the state of an object (we call these observers) or modify the state of an object (we call these mutators). An object produced by(make-counter) provides three methods: reset! (a mutator), next! (a mutator), and get-count (an observer). An object is manipulated using the object's methods. We invoke a method on an object by sending the object a message. This is analogous to applying a procedure. A class is a kind of object. Classes are similar to data types. They define a set of possible values and operations (methods in the object terminology) for manipulating those values.
  • 10. We also need procedures for creating new objects, such as the make- counterprocedure above. We call these constructors. By convention, we call the constructor for a class make- where `` is the name of the class. Hence, an instance of the counter class is the result produced when the make- counterprocedure is applied.