SlideShare a Scribd company logo
1 of 4
9.3 Mutable pairs and lists
The Pair datatype introduced in Chapter 5 is immutable. This means that once a Pair is
created, the values in its cells cannot be changed.1
The MutablePair datatype is a mutable pair.
A MutablePair is constructed usingmcons, which is similar to cons but produces a
MutablePair.
The parts of a MutablePair can be extracted using the mcar and mcdr procedures, which
behave analogously to the car and cdr procedures.
A MutablePair is a distinct datatype from a Pair; it is an error to apply car to a
MutablePair, or to apply mcar to an immutable Pair.
The MutablePair datatype also provides two procedures that change the values in the
cells of a MutablePair:
set-mcar!: MutablePair ×× Value →→ Void: Replaces the value in the first cell of
the MutablePair with the value of the second input.
set-mcdr!: MutablePair ×× Value →→ Void: Replaces the value in the second cell of the
MutablePair with the value of the second input.
The Void result type indicates that set-mcar! and set-mcdr! produce no output.
Here are some interactions using a MutablePair:
> (define pair (mcons 1 2))
> (set-mcar! pair 3)
> pair (3 . 2)
> (set-mcdr! pair 4)
> pair (3 . 4)
The set-mcdr! procedure allows us to create a pair where the second cell of the pair
is itself: (set-mcdr! pair pair). This produces the rather frightening object shown in Figure
9.5.
Figure 9.5: Mutable pair created by evaluating (set-mcdr! pair pair)
Every time we apply mcdr to pair, we get the same pair as the output. Hence, the value of
(mcar (mcdr (mcdr (mcdr pair)))) is 3.
We can also create objects
example, (define mstruct
(cons
that combine mutable and immutable Pairs. For
(mcons 1 2) 3)) defines mstruct as an immutable
Paircontaining a MutablePair in its first cell.
Since the outer Pair is immutable, we cannot change the objects in its cells. Thus, the
second cell ofmstruct always contains the value 3. We can, however, change the values in
the cells of the mutable pair in its first cell. For example, (set-mcar! (car mstruct)
7) replaces the value in the first cell of the MutablePair in the first cell ofmstruct.
Mutable Lists. As we used immutable Pairs to build immutable Lists, we can
use MutablePairs to construct MutableLists.
A MutableList is either null or a MutablePair whose second cell contains a MutableList.
The MutableList type is defined by a library. To use it, evaluate the
following expression: (require racket/mpair).
All of the examples in this chapter assume this expression has been evaluated.
This library defines the mlist procedure that is similar to the list procedure, but
produces a MutableList instead of an immutable List. For example, (mlist 1 2 3)
produces the structure shown inFigure 9.6.
Figure 9.6: MutableList created by evaluating (mlist 1 2 3)
Each node in the list is a MutablePair, so
mcdr! procedures to change the values in the cells.
we can use the set-mcar! and set-
> (define m1 (mlist 1 2 3))
> (set-mcar! (mcdr m1) 5)
> (set-mcar! (mcdr (mcdr m1)) 0)
> m1
{1 5 0}; DrRacket denotes MutableLists using curly brackets.
Many of the list procedures from Chapter 5 can be directly translated to work on
mutable lists. For example, we can define mlist-length as:
(define (mlist-length m)
(if (null? m) 0 (+ 1 (mlist-length (mcdr m)))))
As shown in Exercise 9.4, though, we need to be careful when using mcdr to
recurse through a MutableList since structures created with MutablePairs can include
circular pointers.

More Related Content

Viewers also liked

Viewers also liked (18)

Regular expressions h1
Regular expressions h1Regular expressions h1
Regular expressions h1
 
expressions
expressionsexpressions
expressions
 
modeling computing
modeling computingmodeling computing
modeling computing
 
developing complex_programs
developing complex_programsdeveloping complex_programs
developing complex_programs
 
recursive transition_networks
recursive transition_networksrecursive transition_networks
recursive transition_networks
 
inheritance
inheritanceinheritance
inheritance
 
parser
parserparser
parser
 
measuring computing_power
measuring computing_powermeasuring computing_power
measuring computing_power
 
languages
languageslanguages
languages
 
1.3 applications, issues
1.3 applications, issues1.3 applications, issues
1.3 applications, issues
 
processes
processesprocesses
processes
 
histry of_computing_machines
histry of_computing_machineshistry of_computing_machines
histry of_computing_machines
 
Binary trees
Binary treesBinary trees
Binary trees
 
Quicksort
QuicksortQuicksort
Quicksort
 
Normal forms cfg
Normal forms   cfgNormal forms   cfg
Normal forms cfg
 
TM - Techniques
TM - TechniquesTM - Techniques
TM - Techniques
 
Pumping lemma for regular set h1
Pumping lemma for regular set h1Pumping lemma for regular set h1
Pumping lemma for regular set h1
 
Basics of data structure
Basics of data structureBasics of data structure
Basics of data structure
 

Similar to mutable pairs_and_lists

Task Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfTask Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdf
acsmadurai
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDY
Rajeshkumar Reddy
 
Adv Func Mater 2014_24_1364-1371
Adv Func Mater 2014_24_1364-1371Adv Func Mater 2014_24_1364-1371
Adv Func Mater 2014_24_1364-1371
Subrata Ghosh
 

Similar to mutable pairs_and_lists (20)

pairs
pairspairs
pairs
 
matlab Lesson 1
matlab Lesson 1matlab Lesson 1
matlab Lesson 1
 
Copy on write
Copy on writeCopy on write
Copy on write
 
Task Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfTask Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdf
 
06 linked list
06 linked list06 linked list
06 linked list
 
Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’ Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’
 
C programming , array 2020
C programming , array 2020C programming , array 2020
C programming , array 2020
 
meng.ppt
meng.pptmeng.ppt
meng.ppt
 
A new dna based approach of generating keydependentmixcolumns
A new dna based approach of generating keydependentmixcolumnsA new dna based approach of generating keydependentmixcolumns
A new dna based approach of generating keydependentmixcolumns
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDY
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
Chem modiagram en
Chem modiagram enChem modiagram en
Chem modiagram en
 
How to make fewer errors at the stage of code writing. Part N3.
How to make fewer errors at the stage of code writing. Part N3.How to make fewer errors at the stage of code writing. Part N3.
How to make fewer errors at the stage of code writing. Part N3.
 
Proc sql tips
Proc sql tipsProc sql tips
Proc sql tips
 
handout6.pdf
handout6.pdfhandout6.pdf
handout6.pdf
 
Adv Func Mater 2014_24_1364-1371
Adv Func Mater 2014_24_1364-1371Adv Func Mater 2014_24_1364-1371
Adv Func Mater 2014_24_1364-1371
 
Digital Communication Exam Help
Digital Communication Exam HelpDigital Communication Exam Help
Digital Communication Exam Help
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
 
C%20ARRAYS.pdf.pdf
C%20ARRAYS.pdf.pdfC%20ARRAYS.pdf.pdf
C%20ARRAYS.pdf.pdf
 

More from Rajendran

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

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 

Recently uploaded (20)

UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food Additives
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
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Ữ Â...
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path 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 TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 

mutable pairs_and_lists

  • 1. 9.3 Mutable pairs and lists The Pair datatype introduced in Chapter 5 is immutable. This means that once a Pair is created, the values in its cells cannot be changed.1 The MutablePair datatype is a mutable pair. A MutablePair is constructed usingmcons, which is similar to cons but produces a MutablePair. The parts of a MutablePair can be extracted using the mcar and mcdr procedures, which behave analogously to the car and cdr procedures. A MutablePair is a distinct datatype from a Pair; it is an error to apply car to a MutablePair, or to apply mcar to an immutable Pair. The MutablePair datatype also provides two procedures that change the values in the cells of a MutablePair: set-mcar!: MutablePair ×× Value →→ Void: Replaces the value in the first cell of the MutablePair with the value of the second input. set-mcdr!: MutablePair ×× Value →→ Void: Replaces the value in the second cell of the MutablePair with the value of the second input.
  • 2. The Void result type indicates that set-mcar! and set-mcdr! produce no output. Here are some interactions using a MutablePair: > (define pair (mcons 1 2)) > (set-mcar! pair 3) > pair (3 . 2) > (set-mcdr! pair 4) > pair (3 . 4) The set-mcdr! procedure allows us to create a pair where the second cell of the pair is itself: (set-mcdr! pair pair). This produces the rather frightening object shown in Figure 9.5. Figure 9.5: Mutable pair created by evaluating (set-mcdr! pair pair) Every time we apply mcdr to pair, we get the same pair as the output. Hence, the value of (mcar (mcdr (mcdr (mcdr pair)))) is 3. We can also create objects example, (define mstruct (cons that combine mutable and immutable Pairs. For (mcons 1 2) 3)) defines mstruct as an immutable Paircontaining a MutablePair in its first cell. Since the outer Pair is immutable, we cannot change the objects in its cells. Thus, the second cell ofmstruct always contains the value 3. We can, however, change the values in
  • 3. the cells of the mutable pair in its first cell. For example, (set-mcar! (car mstruct) 7) replaces the value in the first cell of the MutablePair in the first cell ofmstruct. Mutable Lists. As we used immutable Pairs to build immutable Lists, we can use MutablePairs to construct MutableLists. A MutableList is either null or a MutablePair whose second cell contains a MutableList. The MutableList type is defined by a library. To use it, evaluate the following expression: (require racket/mpair). All of the examples in this chapter assume this expression has been evaluated. This library defines the mlist procedure that is similar to the list procedure, but produces a MutableList instead of an immutable List. For example, (mlist 1 2 3) produces the structure shown inFigure 9.6. Figure 9.6: MutableList created by evaluating (mlist 1 2 3) Each node in the list is a MutablePair, so mcdr! procedures to change the values in the cells. we can use the set-mcar! and set- > (define m1 (mlist 1 2 3)) > (set-mcar! (mcdr m1) 5) > (set-mcar! (mcdr (mcdr m1)) 0) > m1 {1 5 0}; DrRacket denotes MutableLists using curly brackets.
  • 4. Many of the list procedures from Chapter 5 can be directly translated to work on mutable lists. For example, we can define mlist-length as: (define (mlist-length m) (if (null? m) 0 (+ 1 (mlist-length (mcdr m))))) As shown in Exercise 9.4, though, we need to be careful when using mcdr to recurse through a MutableList since structures created with MutablePairs can include circular pointers.