SlideShare una empresa de Scribd logo
1 de 2
Descargar para leer sin conexión
CS 94SI Assignment #2 – Object-Oriented Programming 
Due: Before class on Wednesday, April 16, 2008 
E-mail to: cs94si-spr0708-staff@lists.stanford.edu 
Exercise – Sets as Objects 
Last week we saw an implementation of sets that represented them as functions on Ints. This week, we 
will take a more object-oriented approach. Consider the following trait (included in the starter code, 
Assignment2.scala): 
trait AbstractSet { 
def contains(n: Int): Boolean 
def add(n: Int): AbstractSet 
def remove(n: Int): AbstractSet 
def addAll(lst: Iterable[Int]): AbstractSet = 
lst.foldLeft(this)((s, elem) => s add elem) 
def removeAll(lst: Iterable[Int]): AbstractSet = 
lst.foldLeft(this)((s, elem) => s remove elem) 
} 
Traits are almost like Java interfaces. They can specify methods that concrete classes must implement 
in order to mix-in the trait. In this example, the AbstractSet trait has three methods that concrete set 
classes must implement: a method to determine membership (contains), a method to add a member 
(add), and a method to remove a member (remove). 
Unlike Java interfaces, traits can also implement methods. These methods are included (for free) in any 
class that mixes in the trait. The AbstractSet trait has two such methods: a method to add an entire 
List of members (addAll) and a method to remove an entire List of members (removeAll). These 
methods are implemented in the trait itself, even though they rely on methods that have no 
implementation yet. (Don’t worry if you don’t understand the implementation of addAll and 
removeAll, just know that they work as advertised.) 
a) Write a concrete class MutableSet that extends the AbstractSet trait and implements the 
three methods that that trait requires. As its name suggests, your class should be mutable. That 
is, calling the add or remove methods on a MutableSet should modify the instance of the set on 
which the method was called, such that it now contains (or no longer contains), the specified 
Int. 
Note that the AbstractSet trait specifies that the add and remove methods must return an 
AbstractSet. In the case of MutableSet, it is sufficient to return the current set (this). This 
has been implemented for you in the starter code. (Remember that using the return keyword is 
optional; any code block automatically returns its last expression.) 
There are many ways to implement MutableSet. This assignment is purposefully open-ended. 
You may want to look into collections like List[Int] or Array[Int] in the standard library. 
(Granted, the standard library also includes Set collections. Don’t “cheat” and implement your 
MutableSet with a Set from the standard library.) Regardless of your implementation choices, 
the starter code includes some “unit tests” that your MutableSet should pass. 
b) Write a concrete class ImmutableSet that extends the AbstractSet trait and implements the 
three methods that that trait requires. As its name suggests, your class should be immutable.
That is, calling the add or remove methods on an ImmutableSet should not modify the 
instance of the set on which the method was called. Instead, the method should return a new set 
which contains all the previous elements plus the added element (or minus the removed 
element). Hopefully this motivates the return type requirements of the Set trait. 
Again, this is assignment is purposefully open-ended; there are many ways to implement 
ImmutableSet. People coming from Java or similar languages often find it difficult to think in 
immutable data types. Be creative. A word of warning, however: it is entirely possible that we 
haven’t covered enough of the language syntax for you to implement ImmutableSet easily. If 
you find yourself getting stuck, e-mail us what you’ve tried so far and we can help you out. 
As with MutableSet, the starter code includes some “unit tests” that your ImmutableSet 
should pass, if implemented correctly. 
c) Since Scala allows method definitions in traits and sets no limit on how many traits can be 
mixed in, this provides for something akin to multiple inheritance. Consider the following trait: 
trait LockingSet extends AbstractSet { 
abstract override def add(n: Int): AbstractSet = 
synchronized { super.add(n) } 
abstract override def remove(n: Int): AbstractSet = 
synchronized { super.remove(n) } 
abstract override def contains(n: Int): Boolean = 
synchronized { super.contains(n) } 
} 
The LockingSet trait can be mixed into any AbstractSet to create a set that can safely be used 
in the presence of multiple threads. The synchronized keyword works as you would expect 
from Java: each AbstractSet instance has a lock that must be acquired before the synchronized 
method can be performed. (Note: In reality, synchronized is not a keyword but a method on 
the base AnyRef type.) Given this definition, a thread-safe MutableSet can be instantiated as 
follows: 
val s = new MutableSet with LockingSet 
Now write a trait LoggingSet that extends the AbstractSet trait and provides logging 
functionality. Your trait should write to standard output (using the println function) each time 
the contains, add or remove methods are called. 
Now a MutableSet that is both thread-safe and logs its usage to standard output can be 
instantiated as follows: 
val s = new MutableSet with LoggingSet with LockingSet 
Note that our definitions for LockingSet and LoggingSet are agnostic to the actual 
implementation of our set. These traits can just as easily and without modification be mixed into 
our ImmutableSet class. 
d) Do you expect there to be a difference between MutableSet with LoggingSet with 
LockingSet and MutableSet with LockingSet with LoggingSet? What might that 
difference be? 
e) Does it make sense to mix the LockingSet trait into an ImmutableSet? Why or why not? 
Please hand in all the code you’ve written for this assignment.

Más contenido relacionado

La actualidad más candente

Using Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingUsing Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingMike Clement
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
Wrapper class (130240116056)
Wrapper class (130240116056)Wrapper class (130240116056)
Wrapper class (130240116056)Akshay soni
 
function overloading
function overloadingfunction overloading
function overloadingAvaniNakum
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vectornurkhaledah
 
Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector classNontawat Wongnuk
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Abid Kohistani
 
PATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and JavaPATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and JavaMichael Heron
 
Covariance, contravariance 觀念分享
Covariance, contravariance 觀念分享Covariance, contravariance 觀念分享
Covariance, contravariance 觀念分享LearningTech
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programmingTaseerRao
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISPDevnology
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glanceKnoldus Inc.
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?RAKESH P
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12Vishal Dutt
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classesteach4uin
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perlsana mateen
 

La actualidad más candente (20)

Using Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingUsing Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit Testing
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Wrapper class (130240116056)
Wrapper class (130240116056)Wrapper class (130240116056)
Wrapper class (130240116056)
 
function overloading
function overloadingfunction overloading
function overloading
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
 
Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector class
 
Generics C#
Generics C#Generics C#
Generics C#
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)
 
PATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and JavaPATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and Java
 
Covariance, contravariance 觀念分享
Covariance, contravariance 觀念分享Covariance, contravariance 觀念分享
Covariance, contravariance 觀念分享
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Introduction to Preprocessors
Introduction to PreprocessorsIntroduction to Preprocessors
Introduction to Preprocessors
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12
 
Pointer in c++ part2
Pointer in c++ part2Pointer in c++ part2
Pointer in c++ part2
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
Tuple
TupleTuple
Tuple
 

Destacado

41 nosso lar convocados à luta
41 nosso lar  convocados à luta41 nosso lar  convocados à luta
41 nosso lar convocados à lutaFatoze
 

Destacado (8)

A02
A02A02
A02
 
A05
A05A05
A05
 
A06
A06A06
A06
 
A01
A01A01
A01
 
A07
A07A07
A07
 
A03
A03A03
A03
 
Reed lecture 2 midterm
Reed lecture 2 midtermReed lecture 2 midterm
Reed lecture 2 midterm
 
41 nosso lar convocados à luta
41 nosso lar  convocados à luta41 nosso lar  convocados à luta
41 nosso lar convocados à luta
 

Similar a A04

Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)SURBHI SAROHA
 
Java collections
Java collectionsJava collections
Java collectionspadmad2291
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxeyemitra1
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxsmile790243
 
Hash set (java platform se 8 )
Hash set (java platform se 8 )Hash set (java platform se 8 )
Hash set (java platform se 8 )charan kumar
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptxSoniaKapoor56
 
Coding Component (50)Weve provided you with an implementation .docx
Coding Component (50)Weve provided you with an implementation .docxCoding Component (50)Weve provided you with an implementation .docx
Coding Component (50)Weve provided you with an implementation .docxmary772
 

Similar a A04 (20)

Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
Java Unit 2(part 3)
Java Unit 2(part 3)Java Unit 2(part 3)
Java Unit 2(part 3)
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Java.util
Java.utilJava.util
Java.util
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
Java collections
Java collectionsJava collections
Java collections
 
Ch03
Ch03Ch03
Ch03
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
 
Hash set (java platform se 8 )
Hash set (java platform se 8 )Hash set (java platform se 8 )
Hash set (java platform se 8 )
 
Collections
CollectionsCollections
Collections
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Java mcq
Java mcqJava mcq
Java mcq
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Coding Component (50)Weve provided you with an implementation .docx
Coding Component (50)Weve provided you with an implementation .docxCoding Component (50)Weve provided you with an implementation .docx
Coding Component (50)Weve provided you with an implementation .docx
 

Más de lksoo

Más de lksoo (20)

Lo48
Lo48Lo48
Lo48
 
Lo43
Lo43Lo43
Lo43
 
Lo39
Lo39Lo39
Lo39
 
Lo37
Lo37Lo37
Lo37
 
Lo27
Lo27Lo27
Lo27
 
Lo17
Lo17Lo17
Lo17
 
Lo12
Lo12Lo12
Lo12
 
T3
T3T3
T3
 
T2
T2T2
T2
 
T1
T1T1
T1
 
T4
T4T4
T4
 
P5
P5P5
P5
 
P4
P4P4
P4
 
P3
P3P3
P3
 
P1
P1P1
P1
 
P2
P2P2
P2
 
L10
L10L10
L10
 
L9
L9L9
L9
 
L8
L8L8
L8
 
L7
L7L7
L7
 

Último

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 17Celine George
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
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.pptxAreebaZafar22
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
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 FellowsMebane Rash
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 

Último (20)

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
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
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
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
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
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 

A04

  • 1. CS 94SI Assignment #2 – Object-Oriented Programming Due: Before class on Wednesday, April 16, 2008 E-mail to: cs94si-spr0708-staff@lists.stanford.edu Exercise – Sets as Objects Last week we saw an implementation of sets that represented them as functions on Ints. This week, we will take a more object-oriented approach. Consider the following trait (included in the starter code, Assignment2.scala): trait AbstractSet { def contains(n: Int): Boolean def add(n: Int): AbstractSet def remove(n: Int): AbstractSet def addAll(lst: Iterable[Int]): AbstractSet = lst.foldLeft(this)((s, elem) => s add elem) def removeAll(lst: Iterable[Int]): AbstractSet = lst.foldLeft(this)((s, elem) => s remove elem) } Traits are almost like Java interfaces. They can specify methods that concrete classes must implement in order to mix-in the trait. In this example, the AbstractSet trait has three methods that concrete set classes must implement: a method to determine membership (contains), a method to add a member (add), and a method to remove a member (remove). Unlike Java interfaces, traits can also implement methods. These methods are included (for free) in any class that mixes in the trait. The AbstractSet trait has two such methods: a method to add an entire List of members (addAll) and a method to remove an entire List of members (removeAll). These methods are implemented in the trait itself, even though they rely on methods that have no implementation yet. (Don’t worry if you don’t understand the implementation of addAll and removeAll, just know that they work as advertised.) a) Write a concrete class MutableSet that extends the AbstractSet trait and implements the three methods that that trait requires. As its name suggests, your class should be mutable. That is, calling the add or remove methods on a MutableSet should modify the instance of the set on which the method was called, such that it now contains (or no longer contains), the specified Int. Note that the AbstractSet trait specifies that the add and remove methods must return an AbstractSet. In the case of MutableSet, it is sufficient to return the current set (this). This has been implemented for you in the starter code. (Remember that using the return keyword is optional; any code block automatically returns its last expression.) There are many ways to implement MutableSet. This assignment is purposefully open-ended. You may want to look into collections like List[Int] or Array[Int] in the standard library. (Granted, the standard library also includes Set collections. Don’t “cheat” and implement your MutableSet with a Set from the standard library.) Regardless of your implementation choices, the starter code includes some “unit tests” that your MutableSet should pass. b) Write a concrete class ImmutableSet that extends the AbstractSet trait and implements the three methods that that trait requires. As its name suggests, your class should be immutable.
  • 2. That is, calling the add or remove methods on an ImmutableSet should not modify the instance of the set on which the method was called. Instead, the method should return a new set which contains all the previous elements plus the added element (or minus the removed element). Hopefully this motivates the return type requirements of the Set trait. Again, this is assignment is purposefully open-ended; there are many ways to implement ImmutableSet. People coming from Java or similar languages often find it difficult to think in immutable data types. Be creative. A word of warning, however: it is entirely possible that we haven’t covered enough of the language syntax for you to implement ImmutableSet easily. If you find yourself getting stuck, e-mail us what you’ve tried so far and we can help you out. As with MutableSet, the starter code includes some “unit tests” that your ImmutableSet should pass, if implemented correctly. c) Since Scala allows method definitions in traits and sets no limit on how many traits can be mixed in, this provides for something akin to multiple inheritance. Consider the following trait: trait LockingSet extends AbstractSet { abstract override def add(n: Int): AbstractSet = synchronized { super.add(n) } abstract override def remove(n: Int): AbstractSet = synchronized { super.remove(n) } abstract override def contains(n: Int): Boolean = synchronized { super.contains(n) } } The LockingSet trait can be mixed into any AbstractSet to create a set that can safely be used in the presence of multiple threads. The synchronized keyword works as you would expect from Java: each AbstractSet instance has a lock that must be acquired before the synchronized method can be performed. (Note: In reality, synchronized is not a keyword but a method on the base AnyRef type.) Given this definition, a thread-safe MutableSet can be instantiated as follows: val s = new MutableSet with LockingSet Now write a trait LoggingSet that extends the AbstractSet trait and provides logging functionality. Your trait should write to standard output (using the println function) each time the contains, add or remove methods are called. Now a MutableSet that is both thread-safe and logs its usage to standard output can be instantiated as follows: val s = new MutableSet with LoggingSet with LockingSet Note that our definitions for LockingSet and LoggingSet are agnostic to the actual implementation of our set. These traits can just as easily and without modification be mixed into our ImmutableSet class. d) Do you expect there to be a difference between MutableSet with LoggingSet with LockingSet and MutableSet with LockingSet with LoggingSet? What might that difference be? e) Does it make sense to mix the LockingSet trait into an ImmutableSet? Why or why not? Please hand in all the code you’ve written for this assignment.