SlideShare una empresa de Scribd logo
1 de 10
5.2 Pairs
The simplest structured data construct is a Pair. We draw a Pair as two boxes,
each containing a value. We call each box of a Pair a cell.
Here is a Pair where the first cell has the value 37 and the second cell has the value 42:
Scheme provides built-in procedures for constructing a Pair, and for extracting each cell
from a Pair:conscarcdr
• cons: Value ×× Value →→ Pair :
Evaluates to a Pair whose first cell is the first input and second cell is
the second input. The inputs can be of any type.
• car: Pair →→ Value :
Evaluates to the first cell of the input, which must be a
Pair.• cdr: Pair →→ Value :
Evaluates to the second cell of input, which must be a Pair.
These rather unfortunate names come from the original LISP
implementation on the IBM 704. The name cons is short
for “construct”.
The name car is short for “Contents of the Address part of the Register”
and the name cdr (pronounced “could-er”) is short for “Contents of the
Decrement part of the Register”.
The designers of the original LISP implementation picked the names because of
how pairs could be implemented on the IBM 704 using a single register to store both
parts of a pair, but it is a mistake to name things after details of their
implementation (see Section 5.6).
Unfortunately, the names stuck. We can construct the Pair shown above by
evaluating (cons 37 42). DrRacket displays a Pair by printing the value of each cell
separated by a dot: (37 . 42).
The interactions below show example uses of cons, car, and cdr.
> (define mypair (cons 37 42))
> (car mypair) 37
> (cdr mypair) 42
The values in the cells of a Pair can be any type, including other Pairs. For example, this
definition defines a Pair where each cell of the Pair is itself a Pair:
(define doublepair (cons (cons 1 2) (cons 3 4)))
We can use the car and cdr procedures to
to the
Pair (1
access components of
the doublepairstructure: (car doublepair) evaluates . 2), and (cdr
doublepair) evaluates to the Pair (3 . 4).
We can compose multiple car and cdr applications to extract components from
nested pairs:
> (cdr (car doublepair)) 2
> (car (cdr doublepair)) 3
> ((fcompose cdr cdr) doublepair)``fcompose` from [Section 4.2.1](https://www.otexts.org/node/855)
4
> (car (car (car doublepair)))
car: expects argument of type << pair >>; given 1
The last expression produces an error when it is evaluated since car is applied to
the scalar value 1. The car and cdr procedures can only be applied to an input that is a
Pair.
Hence, an error results when we attempt to apply car to a scalar value. This is an
important property of data: the type of data (e.g., a Pair) defines how it can be used
(e.g., passed as the input to car and cdr).
Every procedure expects a certain type of inputs, and typically produces an error when it
is applied to values of the wrong type.
We can draw the value of doublepair by nesting Pairs within cells:
Drawing Pairs within Pairs within Pairs can get quite difficult, however. For instance,
try drawing (cons 1 (cons 2 (cons 3 (cons 4 5)))) this way.
Instead, we us arrows to point to the contents of cells that are not simple values. This is
the structure of doublepair shown using arrows:
Using arrows to point to cell contents allows us to draw arbitrarily complicated
data structures such as (cons 1 (cons 2 (cons 3 (cons 4 5)))), keeping the cells reasonable
sizes:
Exercise 5.3 Suppose the following definition has been executed:
(define tpair (cons (cons (cons 1 2) (cons 3 4)) 5))
Draw the structure defined by tpair, and give the
expressions.
value of each of the following
(cdr tpair)
(car (car (car
tpair))) (cdr
(cdr (car
tpair))) (car
(cdr (cdr
tpair)))
Exercise 5.4 Write
fromfstruct defined by
expressions that extract each of the four elements
(define fstruct (cons 1 (cons 2
(cons 3 4))))
Exercise 5.5 Give an expression that produces the structure shown below.
5.2.1 Making pairs
Although Scheme provides the built-in procedures cons, car, and cdr for creating
Pairs and accessing their cells, there is nothing magical about these procedures.
We can define procedures with the same behavior ourselves using the subset of Scheme
introduced in Chapter 3.
Here is one way to define the pair procedures (we prepend an s to the names to avoid
confusion with the built-in procedures):
(define (scdr pair) (pair false))
The scons procedure takes the two parts of the Pair as inputs, and produces as output a
procedure. The output procedure takes one input, a selector that determines which of
the two cells of the Pair to output.
If the selector is true, the value of the if expression is the value of the first cell; if the
selector is false, it is the value of the second cell.
The scar and scdr procedures apply a procedure constructed by scons to either true (to
select the first cell in scar) or false (to select the second cell in scdr).
(define (scons a b) (lambda (w) (if w a b)))
(define (scar pair) (pair true))
Exercise 5.6. Convince yourself the definitions of scons, scar, and scdr above work
as expected by following the evaluation rules to evaluate
(scar (scons 1 2))
Exercise 5.7. Show the corresponding definitions of tcar and tcdr that provide the pair
selection behavior for a pair created using tcons defined as:
(define (tcons a b) (lambda (w) (if w b a)))
5.2.2 Triples to octuples
Pairs are useful for representing data that is composed of two parts such as a calendar
date (composed of a number and month), or a playing card (composed of a rank and
suit).
But, what if we want to represent data composed of more than two parts such as a date
(composed of a number, month, and year) or a poker hand consisting of five
playing cards? For more complex data structures, we need data structures that have
more than two components.
A triple has three components. Here is one way to define a triple
datatype:
(define (make-triple
a b
(lambda (w) (if (= w 0) a (if (= w
1) b
c)
c))))
(define (triple-first t) (t 0))
(define (triple-second t) (t 1))
(define (triple-third t) (t 2))
Since a triple has three components we need three different selector values. Another way
to make a triple would be to combine two Pairs. We do this by making a Pair
whose second cell is itself a Pair:
(define (make-triple a
(define (triple-first t) (car t))
(define (triple-second t) (car (cdr t)))
(define (triple-third t) (cdr (cdr t)))
b c) (cons a (cons b c)))
Similarly, we can define a quadruple as a Pair whose second cell is a triple:
We could continue in this manner defining increasingly large tuples.
A triple is a Pair whose second cell is a Pair.
A quadruple is a Pair whose second cell is a triple.
A quintuple is a Pair whose second cell is a quadruple.
⋯⋯
An n+1n+1-uple is a Pair whose second cell is an n-uple.
Building from the simple Pair, we can construct tuples containing any number of
components.
Exercise 5.8. Define a procedure that constructs a quintuple and procedures for
selecting the five elements of a quintuple.
(define (make-quad a b c d) (cons a (make-triple b c d)))
(define (quad-first q) (car q))
(define (quad-second q) (triple-first (cdr q))
(define (quad-third q) (triple-second (cdr q))
(define (quad-fourth q) (triple-third (cdr q))
Exercise 5.9. Another way of thinking of a triple is as a Pair where the first cell is a
Pair and the second cell is a scalar. Provide definitions of make-triple, triple-first, triple-
second, and triple-third for this construct.

Más contenido relacionado

La actualidad más candente

Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be CheckedPhilip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Philip Schwarz
 
Applicative Functor - Part 3
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3Philip Schwarz
 
Generating code from dags
Generating code from dagsGenerating code from dags
Generating code from dagsindhu mathi
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Philip Schwarz
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++Fahim Adil
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaFolding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaPhilip Schwarz
 
The dag representation of basic blocks
The dag representation of basic blocksThe dag representation of basic blocks
The dag representation of basic blocksShabeen Taj
 
String in programming language in c or c++
 String in programming language  in c or c++  String in programming language  in c or c++
String in programming language in c or c++ Samsil Arefin
 
Implementation Of String Functions In C
Implementation Of String Functions In CImplementation Of String Functions In C
Implementation Of String Functions In CFazila Sadia
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesWim Vanderbauwhede
 
Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’ Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’ Philip Schwarz
 
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)Wim Vanderbauwhede
 
C programming - String
C programming - StringC programming - String
C programming - StringAchyut Devkota
 
Managing I/O & String function in C
Managing I/O & String function in CManaging I/O & String function in C
Managing I/O & String function in CAbinaya B
 

La actualidad más candente (20)

Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be Checked
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
 
Applicative Functor - Part 3
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3
 
Generating code from dags
Generating code from dagsGenerating code from dags
Generating code from dags
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
 
Strings
StringsStrings
Strings
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaFolding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
 
Copy on write
Copy on writeCopy on write
Copy on write
 
The dag representation of basic blocks
The dag representation of basic blocksThe dag representation of basic blocks
The dag representation of basic blocks
 
C string
C stringC string
C string
 
Headerfiles
HeaderfilesHeaderfiles
Headerfiles
 
String in programming language in c or c++
 String in programming language  in c or c++  String in programming language  in c or c++
String in programming language in c or c++
 
Implementation Of String Functions In C
Implementation Of String Functions In CImplementation Of String Functions In C
Implementation Of String Functions In C
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic Languages
 
Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’ Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’
 
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
 
C programming - String
C programming - StringC programming - String
C programming - String
 
string in C
string in Cstring in C
string in C
 
Managing I/O & String function in C
Managing I/O & String function in CManaging I/O & String function in C
Managing I/O & String function in C
 

Similar a pairs

The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
 
I have question in c++ program I need the answer as soon as possible.docx
I have question in c++ program I need the answer as soon as possible.docxI have question in c++ program I need the answer as soon as possible.docx
I have question in c++ program I need the answer as soon as possible.docxdelciegreeks
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentationManchireddy Reddy
 
1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docx
1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docx1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docx
1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docxchristiandean12115
 
Ee693 sept2014midsem
Ee693 sept2014midsemEe693 sept2014midsem
Ee693 sept2014midsemGopi Saiteja
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework HelpC++ Homework Help
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
Microsoft Word Practice Exercise Set 2
Microsoft Word   Practice Exercise Set 2Microsoft Word   Practice Exercise Set 2
Microsoft Word Practice Exercise Set 2rampan
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotesSowri Rajan
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptxMrhaider4
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxrohinitalekar1
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptxJawadTanvir
 
Saumya Debray The University of Arizona Tucson
Saumya Debray The University of Arizona TucsonSaumya Debray The University of Arizona Tucson
Saumya Debray The University of Arizona Tucsonjeronimored
 

Similar a pairs (20)

The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
 
I have question in c++ program I need the answer as soon as possible.docx
I have question in c++ program I need the answer as soon as possible.docxI have question in c++ program I need the answer as soon as possible.docx
I have question in c++ program I need the answer as soon as possible.docx
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docx
1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docx1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docx
1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docx
 
Ee693 sept2014midsem
Ee693 sept2014midsemEe693 sept2014midsem
Ee693 sept2014midsem
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
Microsoft Word Practice Exercise Set 2
Microsoft Word   Practice Exercise Set 2Microsoft Word   Practice Exercise Set 2
Microsoft Word Practice Exercise Set 2
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Arrays
ArraysArrays
Arrays
 
Session2
Session2Session2
Session2
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
611+tutorial
611+tutorial611+tutorial
611+tutorial
 
Saumya Debray The University of Arizona Tucson
Saumya Debray The University of Arizona TucsonSaumya Debray The University of Arizona Tucson
Saumya Debray The University of Arizona Tucson
 
Fcm1
Fcm1Fcm1
Fcm1
 
Fcm1
Fcm1Fcm1
Fcm1
 

Más de 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
 

Más de 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
 

Último

Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 

Último (20)

Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 

pairs

  • 1. 5.2 Pairs The simplest structured data construct is a Pair. We draw a Pair as two boxes, each containing a value. We call each box of a Pair a cell. Here is a Pair where the first cell has the value 37 and the second cell has the value 42: Scheme provides built-in procedures for constructing a Pair, and for extracting each cell from a Pair:conscarcdr • cons: Value ×× Value →→ Pair : Evaluates to a Pair whose first cell is the first input and second cell is the second input. The inputs can be of any type. • car: Pair →→ Value : Evaluates to the first cell of the input, which must be a Pair.• cdr: Pair →→ Value : Evaluates to the second cell of input, which must be a Pair. These rather unfortunate names come from the original LISP implementation on the IBM 704. The name cons is short for “construct”. The name car is short for “Contents of the Address part of the Register” and the name cdr (pronounced “could-er”) is short for “Contents of the Decrement part of the Register”.
  • 2. The designers of the original LISP implementation picked the names because of how pairs could be implemented on the IBM 704 using a single register to store both parts of a pair, but it is a mistake to name things after details of their implementation (see Section 5.6). Unfortunately, the names stuck. We can construct the Pair shown above by evaluating (cons 37 42). DrRacket displays a Pair by printing the value of each cell separated by a dot: (37 . 42). The interactions below show example uses of cons, car, and cdr. > (define mypair (cons 37 42)) > (car mypair) 37 > (cdr mypair) 42 The values in the cells of a Pair can be any type, including other Pairs. For example, this definition defines a Pair where each cell of the Pair is itself a Pair: (define doublepair (cons (cons 1 2) (cons 3 4))) We can use the car and cdr procedures to to the Pair (1 access components of the doublepairstructure: (car doublepair) evaluates . 2), and (cdr doublepair) evaluates to the Pair (3 . 4). We can compose multiple car and cdr applications to extract components from nested pairs: > (cdr (car doublepair)) 2 > (car (cdr doublepair)) 3 > ((fcompose cdr cdr) doublepair)``fcompose` from [Section 4.2.1](https://www.otexts.org/node/855) 4 > (car (car (car doublepair))) car: expects argument of type << pair >>; given 1
  • 3. The last expression produces an error when it is evaluated since car is applied to the scalar value 1. The car and cdr procedures can only be applied to an input that is a Pair. Hence, an error results when we attempt to apply car to a scalar value. This is an important property of data: the type of data (e.g., a Pair) defines how it can be used (e.g., passed as the input to car and cdr). Every procedure expects a certain type of inputs, and typically produces an error when it is applied to values of the wrong type. We can draw the value of doublepair by nesting Pairs within cells: Drawing Pairs within Pairs within Pairs can get quite difficult, however. For instance, try drawing (cons 1 (cons 2 (cons 3 (cons 4 5)))) this way.
  • 4. Instead, we us arrows to point to the contents of cells that are not simple values. This is the structure of doublepair shown using arrows: Using arrows to point to cell contents allows us to draw arbitrarily complicated data structures such as (cons 1 (cons 2 (cons 3 (cons 4 5)))), keeping the cells reasonable sizes:
  • 5. Exercise 5.3 Suppose the following definition has been executed: (define tpair (cons (cons (cons 1 2) (cons 3 4)) 5)) Draw the structure defined by tpair, and give the expressions. value of each of the following (cdr tpair) (car (car (car tpair))) (cdr (cdr (car tpair))) (car (cdr (cdr tpair))) Exercise 5.4 Write fromfstruct defined by expressions that extract each of the four elements (define fstruct (cons 1 (cons 2 (cons 3 4)))) Exercise 5.5 Give an expression that produces the structure shown below.
  • 6. 5.2.1 Making pairs Although Scheme provides the built-in procedures cons, car, and cdr for creating Pairs and accessing their cells, there is nothing magical about these procedures. We can define procedures with the same behavior ourselves using the subset of Scheme introduced in Chapter 3. Here is one way to define the pair procedures (we prepend an s to the names to avoid confusion with the built-in procedures): (define (scdr pair) (pair false)) The scons procedure takes the two parts of the Pair as inputs, and produces as output a procedure. The output procedure takes one input, a selector that determines which of the two cells of the Pair to output. If the selector is true, the value of the if expression is the value of the first cell; if the selector is false, it is the value of the second cell. The scar and scdr procedures apply a procedure constructed by scons to either true (to select the first cell in scar) or false (to select the second cell in scdr). (define (scons a b) (lambda (w) (if w a b))) (define (scar pair) (pair true))
  • 7. Exercise 5.6. Convince yourself the definitions of scons, scar, and scdr above work as expected by following the evaluation rules to evaluate (scar (scons 1 2)) Exercise 5.7. Show the corresponding definitions of tcar and tcdr that provide the pair selection behavior for a pair created using tcons defined as: (define (tcons a b) (lambda (w) (if w b a)))
  • 8. 5.2.2 Triples to octuples Pairs are useful for representing data that is composed of two parts such as a calendar date (composed of a number and month), or a playing card (composed of a rank and suit). But, what if we want to represent data composed of more than two parts such as a date (composed of a number, month, and year) or a poker hand consisting of five playing cards? For more complex data structures, we need data structures that have more than two components. A triple has three components. Here is one way to define a triple datatype: (define (make-triple a b (lambda (w) (if (= w 0) a (if (= w 1) b c) c)))) (define (triple-first t) (t 0)) (define (triple-second t) (t 1)) (define (triple-third t) (t 2)) Since a triple has three components we need three different selector values. Another way to make a triple would be to combine two Pairs. We do this by making a Pair whose second cell is itself a Pair: (define (make-triple a (define (triple-first t) (car t)) (define (triple-second t) (car (cdr t))) (define (triple-third t) (cdr (cdr t))) b c) (cons a (cons b c)))
  • 9. Similarly, we can define a quadruple as a Pair whose second cell is a triple: We could continue in this manner defining increasingly large tuples. A triple is a Pair whose second cell is a Pair. A quadruple is a Pair whose second cell is a triple. A quintuple is a Pair whose second cell is a quadruple. ⋯⋯ An n+1n+1-uple is a Pair whose second cell is an n-uple. Building from the simple Pair, we can construct tuples containing any number of components. Exercise 5.8. Define a procedure that constructs a quintuple and procedures for selecting the five elements of a quintuple. (define (make-quad a b c d) (cons a (make-triple b c d))) (define (quad-first q) (car q)) (define (quad-second q) (triple-first (cdr q)) (define (quad-third q) (triple-second (cdr q)) (define (quad-fourth q) (triple-third (cdr q))
  • 10. Exercise 5.9. Another way of thinking of a triple is as a Pair where the first cell is a Pair and the second cell is a scalar. Provide definitions of make-triple, triple-first, triple- second, and triple-third for this construct.