SlideShare a Scribd company logo
5.4 List procedures
Since the List data structure is defined recursively, it is natural to define
recursive procedures to examine and manipulate lists.
Whereas most recursive procedures on inputs that are Numbers usually used 0 as
the base case, for lists the most common base case is null.
With numbers, we make progress by subtracting 1; with lists, we make progress
by using cdr to reduce the length of the input List by one element for each
recursive application.
This means we often break problems involving Lists into figuring out what to do with
the first element of the List and the result of applying the recursive procedure to the rest
of the List.
We can specialize our general problem solving strategy from Chapter 3 for
procedures involving lists:
• Be very optimistic! Since lists themselves are recursive data structures, most
problems involving lists can be solved with recursive procedures. Think of
the simplest version of the problem, something you can already solve. This is the
base case. For lists, this is usually the empty list.
• Consider how you would solve a big version of the problem by using the result for
a slightly smaller version of the problem. This is the recursive case. For lists, the
smaller version of the problem is usually the rest (cdr) of the List.
Combine the base case and the recursive case to solve the problem.
• Next we consider procedures that examine lists by walking through
their elements and producing a scalar value.Section 5.4.2 generalizes these
procedures. In Section 5.4.3, we explore procedures that output lists.
5.4.1 Procedures that examine lists
All of the example procedures in this section take a single List as input
and produce a scalar value that depends on the elements of the List as
output.
These procedures have base cases where the List is empty, and recursive cases
that apply the recursive procedure to the cdr of the input List.
Example 5.1: Length
How many elements are in a given List?1 Our standard recursive problem solving
technique is to “Think of the simplest version of the problem, something you can
already solve.”
For this procedure, the simplest version of the problem is when the input is
the empty list, null. We know the length of the empty list is 0. So, the base case
test is (null? p) and the output for the base case is 0.
For the recursive case, we need to consider the structure of all lists other
thannull. Recall from our definition that a List is either null or (cons 0).
The base case handles the null list; the recursive case must handle a List that is a
Pair of an element and a List. The length of this List is one more than the
length of the List that is the cdr of the Pair.
(define (list-length p) (if (null? p) 0 (+ 1 (list-length (cdr p)))))
Here are a few example applications of our list-length procedure:
> (list-length null) 0
> (list-length (cons 0 null))
1
> (list-length (list 1 2 3 4))
4
Example 5.10: List Sums and Products
First, we define a procedure that takes a List of numbers as input and produces
as output the sum of the numbers in the input List.
As usual, the base case is when the input is null: the sum of an empty list is 0. For
the recursive case, we need to add the value of the first number in the List, to
the sum of the rest of the numbers in the List.
(define (list-sum p)
(if (null? p) 0 (+ (car p) (list-sum (cdr p)))))
We can define list-product similarly, using * in place of +. The base ca
se result cannot be 0, though, since then the final result would always be 0
since any number multiplied by 0 is 0.
We follow the mathematical convention that the product of the empty list is 1.
(define (list-product p)
(if (null? p) 1 (* (car p) (list-product (cdr p)))))
Exercise 5.11. Define a procedure is-list? that takes one input and outputs true
if the input is a List, and false otherwise. Your procedure should behave
identically to the built-in list? procedure, but you should not use list? in your
definition.
Exercise 5.12. Define a procedure list-max that takes a List of non-negative
numbers as its input and produces as its result the value of the greatest
element in the List (or 0 if there are no elements in the input List). For
example, (list-max (list 1 1 2 0)) should evaluate to 2.
Exercise 5.11. Define a procedure is-list? that takes one input and outputs true
if the input is a List, and false otherwise. Your procedure should behave
identically to the built-in list? procedure, but you should not use list? in your
definition.
Exercise 5.12. Define a procedure list-max that takes a List of non-negative
numbers as its input and produces as its result the value of the greatest
element in the List (or 0 if there are no elements in the input List). For
example, (list-max (list 1 1 2 0)) should evaluate to 2.

More Related Content

What's hot

PROLOG: Arithmetic Operations In Prolog
PROLOG: Arithmetic Operations In PrologPROLOG: Arithmetic Operations In Prolog
PROLOG: Arithmetic Operations In Prolog
DataminingTools Inc
 
Linear and Binary search
Linear and Binary searchLinear and Binary search
Linear and Binary search
Nisha Soms
 
Binary search algorithm
Binary search algorithmBinary search algorithm
Binary search algorithm
maamir farooq
 
Binary Search
Binary SearchBinary Search
Binary Search
kunj desai
 
Rahat & juhith
Rahat & juhithRahat & juhith
Rahat & juhith
Rj Juhith
 
An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1
Blue Elephant Consulting
 
Binary search
Binary searchBinary search
Binary search
AparnaKumari31
 
Binary search python
Binary search pythonBinary search python
Binary search python
MaryamAnwar10
 
Array 2
Array 2Array 2
Array 2
Abbott
 
Searching linear & binary search
Searching linear & binary searchSearching linear & binary search
Searching linear & binary search
nikunjandy
 
arrays
arraysarrays
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searching
sajinis3
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
Zia Ush Shamszaman
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
DrRajeshreeKhande
 
Non-Uniform Gap Distribution Library Sort
Non-Uniform Gap Distribution Library SortNon-Uniform Gap Distribution Library Sort
Non-Uniform Gap Distribution Library Sort
IJCSIS Research Publications
 
Binary search
Binary search Binary search
Binary search Raghu nath
 
Searching
SearchingSearching
Searching
Ashim Lamichhane
 
Binary search Algorithm
Binary search AlgorithmBinary search Algorithm
Binary search Algorithm
FazalRehman79
 

What's hot (20)

PROLOG: Arithmetic Operations In Prolog
PROLOG: Arithmetic Operations In PrologPROLOG: Arithmetic Operations In Prolog
PROLOG: Arithmetic Operations In Prolog
 
Linear and Binary search
Linear and Binary searchLinear and Binary search
Linear and Binary search
 
Binary search algorithm
Binary search algorithmBinary search algorithm
Binary search algorithm
 
Chap10
Chap10Chap10
Chap10
 
Binary Search
Binary SearchBinary Search
Binary Search
 
Rahat & juhith
Rahat & juhithRahat & juhith
Rahat & juhith
 
An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1
 
Binary search
Binary searchBinary search
Binary search
 
Binary search python
Binary search pythonBinary search python
Binary search python
 
Array 2
Array 2Array 2
Array 2
 
Searching linear & binary search
Searching linear & binary searchSearching linear & binary search
Searching linear & binary search
 
arrays
arraysarrays
arrays
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searching
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
 
Non-Uniform Gap Distribution Library Sort
Non-Uniform Gap Distribution Library SortNon-Uniform Gap Distribution Library Sort
Non-Uniform Gap Distribution Library Sort
 
Ch05 Black Jack
Ch05  Black  JackCh05  Black  Jack
Ch05 Black Jack
 
Binary search
Binary search Binary search
Binary search
 
Searching
SearchingSearching
Searching
 
Binary search Algorithm
Binary search AlgorithmBinary search Algorithm
Binary search Algorithm
 

Viewers also liked

Tratamiento para crecer el cabello
Tratamiento para crecer el cabelloTratamiento para crecer el cabello
Tratamiento para crecer el cabelloamientqol
 
Proyecto de vida zz
Proyecto de vida zzProyecto de vida zz
Proyecto de vida zzZurdo Cano
 
Cv faisal mehmood-telecommunication
Cv faisal mehmood-telecommunicationCv faisal mehmood-telecommunication
Cv faisal mehmood-telecommunication
Faisal Mehmood
 
My trip in hokkaido
My trip in hokkaidoMy trip in hokkaido
My trip in hokkaidoR. Ayakix
 
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCMNhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
Tien Thao
 
Упасть, чтобы подняться
Упасть, чтобы поднятьсяУпасть, чтобы подняться
Упасть, чтобы подняться
smartnick
 
lazy evaluation
lazy evaluationlazy evaluation
lazy evaluation
Rajendran
 
Volantes #OpPaperStormSv 15 de Septiembre 2012
Volantes #OpPaperStormSv 15 de Septiembre 2012Volantes #OpPaperStormSv 15 de Septiembre 2012
Volantes #OpPaperStormSv 15 de Septiembre 2012paniczone
 
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng tạ...
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng  tạ...Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng  tạ...
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng tạ...
Tien Thao
 
Relaciones entre los Seres Vivos por Sandra Salazar
Relaciones entre los Seres Vivos por Sandra SalazarRelaciones entre los Seres Vivos por Sandra Salazar
Relaciones entre los Seres Vivos por Sandra Salazar
SandraEliSalazar
 
Loichucvui
LoichucvuiLoichucvui
LoichucvuiHa Hoa
 
Dusaodinua
DusaodinuaDusaodinua
Dusaodinua
Ha Hoa
 
Lebenslauf Inna Slobodyanyuk
Lebenslauf Inna SlobodyanyukLebenslauf Inna Slobodyanyuk
Lebenslauf Inna SlobodyanyukInna Slobodyanyuk
 

Viewers also liked (16)

Trampo rods
Trampo rodsTrampo rods
Trampo rods
 
Tratamiento para crecer el cabello
Tratamiento para crecer el cabelloTratamiento para crecer el cabello
Tratamiento para crecer el cabello
 
Nicole mejia
Nicole mejiaNicole mejia
Nicole mejia
 
Proyecto de vida zz
Proyecto de vida zzProyecto de vida zz
Proyecto de vida zz
 
Cv faisal mehmood-telecommunication
Cv faisal mehmood-telecommunicationCv faisal mehmood-telecommunication
Cv faisal mehmood-telecommunication
 
My trip in hokkaido
My trip in hokkaidoMy trip in hokkaido
My trip in hokkaido
 
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCMNhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
 
Упасть, чтобы подняться
Упасть, чтобы поднятьсяУпасть, чтобы подняться
Упасть, чтобы подняться
 
lazy evaluation
lazy evaluationlazy evaluation
lazy evaluation
 
Volantes #OpPaperStormSv 15 de Septiembre 2012
Volantes #OpPaperStormSv 15 de Septiembre 2012Volantes #OpPaperStormSv 15 de Septiembre 2012
Volantes #OpPaperStormSv 15 de Septiembre 2012
 
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng tạ...
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng  tạ...Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng  tạ...
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng tạ...
 
Bokstavelig!
Bokstavelig!Bokstavelig!
Bokstavelig!
 
Relaciones entre los Seres Vivos por Sandra Salazar
Relaciones entre los Seres Vivos por Sandra SalazarRelaciones entre los Seres Vivos por Sandra Salazar
Relaciones entre los Seres Vivos por Sandra Salazar
 
Loichucvui
LoichucvuiLoichucvui
Loichucvui
 
Dusaodinua
DusaodinuaDusaodinua
Dusaodinua
 
Lebenslauf Inna Slobodyanyuk
Lebenslauf Inna SlobodyanyukLebenslauf Inna Slobodyanyuk
Lebenslauf Inna Slobodyanyuk
 

Similar to list procedures

Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docxAssg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
jane3dyson92312
 
Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docxAssg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
festockton
 
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docxAssg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
festockton
 
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUESPYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
vanithasivdc
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
infanciaj
 
MODULE-2.pptx
MODULE-2.pptxMODULE-2.pptx
MODULE-2.pptx
ASRPANDEY
 
best first-sort
best first-sortbest first-sort
best first-sort
Rajendran
 
Chapter3.pptx
Chapter3.pptxChapter3.pptx
Chapter3.pptx
ASMAALWADEE2
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
LecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdfLecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdf
AmirMohamedNabilSale
 
expressions
expressionsexpressions
expressions
Rajendran
 
LISP: Introduction to lisp
LISP: Introduction to lispLISP: Introduction to lisp
LISP: Introduction to lisp
DataminingTools Inc
 
LISP: Introduction To Lisp
LISP: Introduction To LispLISP: Introduction To Lisp
LISP: Introduction To Lisp
LISP Content
 
List,Stacks and Queues.pptx
List,Stacks and Queues.pptxList,Stacks and Queues.pptx
List,Stacks and Queues.pptx
UmatulSaboohSaleem1
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
Asst.prof M.Gokilavani
 
AI Programming language (LISP)
AI Programming language (LISP)AI Programming language (LISP)
AI Programming language (LISP)
SURBHI SAROHA
 
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List AlgorithmsAn Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List Algorithms
Blue Elephant Consulting
 
Due November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdfDue November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdf
abibagschennai
 

Similar to list procedures (20)

Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docxAssg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
 
Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docxAssg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
Assg 05 QuicksortCOSC 2336 Data StructuresObjectives.docx
 
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docxAssg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
 
pyton Notes6
 pyton Notes6 pyton Notes6
pyton Notes6
 
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUESPYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
MODULE-2.pptx
MODULE-2.pptxMODULE-2.pptx
MODULE-2.pptx
 
best first-sort
best first-sortbest first-sort
best first-sort
 
Chapter3.pptx
Chapter3.pptxChapter3.pptx
Chapter3.pptx
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
 
LecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdfLecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdf
 
expressions
expressionsexpressions
expressions
 
LISP: Introduction to lisp
LISP: Introduction to lispLISP: Introduction to lisp
LISP: Introduction to lisp
 
LISP: Introduction To Lisp
LISP: Introduction To LispLISP: Introduction To Lisp
LISP: Introduction To Lisp
 
List,Stacks and Queues.pptx
List,Stacks and Queues.pptxList,Stacks and Queues.pptx
List,Stacks and Queues.pptx
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
AI Programming language (LISP)
AI Programming language (LISP)AI Programming language (LISP)
AI Programming language (LISP)
 
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List AlgorithmsAn Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List Algorithms
 
Q
QQ
Q
 
Due November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdfDue November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdf
 

More from Rajendran

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

BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 

Recently uploaded (20)

BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 

list procedures

  • 1. 5.4 List procedures Since the List data structure is defined recursively, it is natural to define recursive procedures to examine and manipulate lists. Whereas most recursive procedures on inputs that are Numbers usually used 0 as the base case, for lists the most common base case is null. With numbers, we make progress by subtracting 1; with lists, we make progress by using cdr to reduce the length of the input List by one element for each recursive application. This means we often break problems involving Lists into figuring out what to do with the first element of the List and the result of applying the recursive procedure to the rest of the List.
  • 2. We can specialize our general problem solving strategy from Chapter 3 for procedures involving lists: • Be very optimistic! Since lists themselves are recursive data structures, most problems involving lists can be solved with recursive procedures. Think of the simplest version of the problem, something you can already solve. This is the base case. For lists, this is usually the empty list. • Consider how you would solve a big version of the problem by using the result for a slightly smaller version of the problem. This is the recursive case. For lists, the smaller version of the problem is usually the rest (cdr) of the List. Combine the base case and the recursive case to solve the problem. • Next we consider procedures that examine lists by walking through their elements and producing a scalar value.Section 5.4.2 generalizes these procedures. In Section 5.4.3, we explore procedures that output lists.
  • 3. 5.4.1 Procedures that examine lists All of the example procedures in this section take a single List as input and produce a scalar value that depends on the elements of the List as output. These procedures have base cases where the List is empty, and recursive cases that apply the recursive procedure to the cdr of the input List. Example 5.1: Length How many elements are in a given List?1 Our standard recursive problem solving technique is to “Think of the simplest version of the problem, something you can already solve.” For this procedure, the simplest version of the problem is when the input is the empty list, null. We know the length of the empty list is 0. So, the base case test is (null? p) and the output for the base case is 0. For the recursive case, we need to consider the structure of all lists other thannull. Recall from our definition that a List is either null or (cons 0). The base case handles the null list; the recursive case must handle a List that is a Pair of an element and a List. The length of this List is one more than the length of the List that is the cdr of the Pair.
  • 4. (define (list-length p) (if (null? p) 0 (+ 1 (list-length (cdr p))))) Here are a few example applications of our list-length procedure: > (list-length null) 0 > (list-length (cons 0 null)) 1 > (list-length (list 1 2 3 4)) 4 Example 5.10: List Sums and Products First, we define a procedure that takes a List of numbers as input and produces as output the sum of the numbers in the input List. As usual, the base case is when the input is null: the sum of an empty list is 0. For the recursive case, we need to add the value of the first number in the List, to the sum of the rest of the numbers in the List. (define (list-sum p) (if (null? p) 0 (+ (car p) (list-sum (cdr p))))) We can define list-product similarly, using * in place of +. The base ca se result cannot be 0, though, since then the final result would always be 0 since any number multiplied by 0 is 0. We follow the mathematical convention that the product of the empty list is 1. (define (list-product p) (if (null? p) 1 (* (car p) (list-product (cdr p)))))
  • 5. Exercise 5.11. Define a procedure is-list? that takes one input and outputs true if the input is a List, and false otherwise. Your procedure should behave identically to the built-in list? procedure, but you should not use list? in your definition. Exercise 5.12. Define a procedure list-max that takes a List of non-negative numbers as its input and produces as its result the value of the greatest element in the List (or 0 if there are no elements in the input List). For example, (list-max (list 1 1 2 0)) should evaluate to 2.
  • 6. Exercise 5.11. Define a procedure is-list? that takes one input and outputs true if the input is a List, and false otherwise. Your procedure should behave identically to the built-in list? procedure, but you should not use list? in your definition. Exercise 5.12. Define a procedure list-max that takes a List of non-negative numbers as its input and produces as its result the value of the greatest element in the List (or 0 if there are no elements in the input List). For example, (list-max (list 1 1 2 0)) should evaluate to 2.