SlideShare a Scribd company logo
1 of 6
4.3 Recursive problem solving
In the previous section, we used functional composition to break a problem into
two procedures that can be composed to produce the desired output.
A particularly useful variation on this is when we can break a problem into a
smaller version of the original problem.
The goal is to be able to feed the output of one application of the procedure back into
the same procedure as its input for the next application, as shown inFigure 4.3.
Fig
ure 4.3: Circular Composition.
Here’s a corresponding Scheme procedure:
(define f (lambda (n) (f n)))
Of course, this doesn’t work very well!1 Every application of f results in another
application of f to evaluate.
This never stops — no output is ever produced and the interpreter will keep
evaluating applications of f until it is stopped or runs out of memory.
We need a way to make progress and eventually stop, instead of going around in
circles. To make progress, each subsequent application should have a smallerinput.
Then, the applications stop when the input to the procedure is simple enough that
the output is already known.
The stopping condition is called thebase case, similarly to the grammar rules
in Section 2.4. In our grammar examples, the base case involved replacing the
nonterminal with nothing (e.g.,MoreDigits ::⇒⇒ ϵϵ) or with a terminal
(e.g., Noun ::⇒⇒ Alice). In recursive procedures, the base case will provide a solution
for some input for which the problem is so simple we already know the answer. When
the input is a number, this is often (but not necessarily) when the input is 0 or 1.
To define a recursive procedure, we use an if expression to test if the input matches
the base case input.
If it does, the consequent expression is the known answer for the base case. Otherwise,
the recursive case applies the procedure again but with a smaller input.
That application needs to make progress towards reaching the base case. This means,
the input has to change in a way that gets closer to the base case input.
If the base case is for 0, and the original input is a positive number, one way to get
closer to the base case input is to subtract 1 from the input value with each
recursive application.
This evaluation spiral is depicted in Figure 4.4. With each subsequent recursive call, the
input gets smaller, eventually reaching the base case.
For the base case application, a result is returned to the previous application. This
is passed back up the spiral to produce the final output.
Keeping track of where we are in a recursive evaluation is similar to keeping track of
the subnetworks in an RTN traversal.
The evaluator needs to keep track of where to return after each recursive evaluation
completes, similarly to how we needed to keep track of the stack of subnetworks to
know how to proceed in an RTN traversal.
Fig
ure 4.4: Recursive Composition.
Here is the corresponding procedure:
(define g (lambda (n)
(if (= n 0) 1
(g (- n 1)))))
Unlike the earlier circular f procedure, if we apply g to any non-negative integer it will
eventually produce an output. For example, consider evaluating (g 2).
When we evaluate the first application, the value of the parameter n is 2, so the predicate
expression (= n 0) evaluates to false and the value of the procedure body is the value of
the alternate expression, (g (- n 1)).
The subexpression, (- n 1) evaluates to 1, so the result is the result of applying g to 1.
As with the previous application, this leads to the application, (g (- n 1)), but this time
the value of n is 1, so (- n 1) evaluates to 0.
The next application leads to the application, (g 0). This time, the predicate expression
evaluates to true and we have reached the base case.
The consequent expression is just 1, so no further applications of g are performed and
this is the result of the application (g 0).
This is returned as the result of the (g 1) application in the previous recursive call, and
then as the output of the original (g 2) application.
We can think of the recursive evaluation as winding until the base case is reached,
and then unwinding the outputs back to the original application.
For this procedure, the output is not very interesting: no matter what positive
number we apply g to, the eventual result is 1.
To solve interesting problems with recursive procedures, we need to accumulate results
as the recursive applications wind or unwind.
This is returned as the result of the (g 1) application in the previous recursive call, and
then as the output of the original (g 2) application.
We can think of the recursive evaluation as winding until the base case is reached,
and then unwinding the outputs back to the original application.
For this procedure, the output is not very interesting: no matter what positive
number we apply g to, the eventual result is 1.
To solve interesting problems with recursive procedures, we need to accumulate results
as the recursive applications wind or unwind.

More Related Content

What's hot

lazy evaluation
lazy evaluationlazy evaluation
lazy evaluationRajendran
 
Type conversion in c
Type conversion in cType conversion in c
Type conversion in cSHIKHA GAUTAM
 
Introduction to C Programming
Introduction to C Programming Introduction to C Programming
Introduction to C Programming vampugani
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes NUST Stuff
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of PrecedenceMuhammad Hammad Waseem
 
Domain and range (linear, quadratic, rational functions)
Domain and range (linear, quadratic, rational functions)Domain and range (linear, quadratic, rational functions)
Domain and range (linear, quadratic, rational functions)Rose Mary Tania Arini
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programmingRumman Ansari
 
Notes: Verilog Part 1 - Overview - Hierarchical Modeling Concepts - Basics
Notes: Verilog Part 1 - Overview - Hierarchical Modeling Concepts - BasicsNotes: Verilog Part 1 - Overview - Hierarchical Modeling Concepts - Basics
Notes: Verilog Part 1 - Overview - Hierarchical Modeling Concepts - BasicsJay Baxi
 
Highorderfunctions in swift
Highorderfunctions in swiftHighorderfunctions in swift
Highorderfunctions in swiftAhmet Keskin
 
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++Muhammad Hammad Waseem
 
Lecture 4: Functions
Lecture 4: FunctionsLecture 4: Functions
Lecture 4: FunctionsVivek Bhargav
 

What's hot (20)

[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
 
lazy evaluation
lazy evaluationlazy evaluation
lazy evaluation
 
Type conversion in c
Type conversion in cType conversion in c
Type conversion in c
 
Function Pointer in C
Function Pointer in CFunction Pointer in C
Function Pointer in C
 
Introduction to C Programming
Introduction to C Programming Introduction to C Programming
Introduction to C Programming
 
2 r algebra
2 r algebra2 r algebra
2 r algebra
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes
 
Functions
FunctionsFunctions
Functions
 
Model and Design
Model and Design Model and Design
Model and Design
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
 
Domain and range (linear, quadratic, rational functions)
Domain and range (linear, quadratic, rational functions)Domain and range (linear, quadratic, rational functions)
Domain and range (linear, quadratic, rational functions)
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programming
 
selection structures
selection structuresselection structures
selection structures
 
Notes: Verilog Part 1 - Overview - Hierarchical Modeling Concepts - Basics
Notes: Verilog Part 1 - Overview - Hierarchical Modeling Concepts - BasicsNotes: Verilog Part 1 - Overview - Hierarchical Modeling Concepts - Basics
Notes: Verilog Part 1 - Overview - Hierarchical Modeling Concepts - Basics
 
Highorderfunctions in swift
Highorderfunctions in swiftHighorderfunctions in swift
Highorderfunctions in swift
 
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
 
Lecture 4: Functions
Lecture 4: FunctionsLecture 4: Functions
Lecture 4: Functions
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 

Similar to recursive problem_solving

Recursion and looping
Recursion and loopingRecursion and looping
Recursion and loopingxcoolanurag
 
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx15AnasKhan
 
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
TIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMSTIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMS
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMSTanya Makkar
 
Recursion | C++ | DSA
Recursion | C++ | DSARecursion | C++ | DSA
Recursion | C++ | DSASumit Pandey
 
2. Linear regression with one variable.pptx
2. Linear regression with one variable.pptx2. Linear regression with one variable.pptx
2. Linear regression with one variable.pptxEmad Nabil
 
Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Deepak John
 
Implementing an 8-chip game based on the A algorithm.pptx
Implementing an 8-chip game based on the A algorithm.pptxImplementing an 8-chip game based on the A algorithm.pptx
Implementing an 8-chip game based on the A algorithm.pptxlwz614595250
 
(Slides) Efficient Evaluation Methods of Elementary Functions Suitable for SI...
(Slides) Efficient Evaluation Methods of Elementary Functions Suitable for SI...(Slides) Efficient Evaluation Methods of Elementary Functions Suitable for SI...
(Slides) Efficient Evaluation Methods of Elementary Functions Suitable for SI...Naoki Shibata
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingJay Nagar
 
Adaptive Parallelization of Queries over Dependent Web Service Calls
Adaptive Parallelization of Queries over Dependent Web Service CallsAdaptive Parallelization of Queries over Dependent Web Service Calls
Adaptive Parallelization of Queries over Dependent Web Service CallsSabesan Manivasakan
 
Unit 2 Modeling of Programs A function maps inputs to out.docx
Unit 2 Modeling of Programs A function maps inputs to out.docxUnit 2 Modeling of Programs A function maps inputs to out.docx
Unit 2 Modeling of Programs A function maps inputs to out.docxdickonsondorris
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms NotesAndres Mendez-Vazquez
 

Similar to recursive problem_solving (20)

Recursion and looping
Recursion and loopingRecursion and looping
Recursion and looping
 
Ann a Algorithms notes
Ann a Algorithms notesAnn a Algorithms notes
Ann a Algorithms notes
 
Daa unit 1
Daa unit 1Daa unit 1
Daa unit 1
 
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
 
DATA STRUCTURE.pdf
DATA STRUCTURE.pdfDATA STRUCTURE.pdf
DATA STRUCTURE.pdf
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURE
 
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
TIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMSTIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMS
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
 
Recursion | C++ | DSA
Recursion | C++ | DSARecursion | C++ | DSA
Recursion | C++ | DSA
 
Thr russian doll search
Thr russian doll searchThr russian doll search
Thr russian doll search
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
2. Linear regression with one variable.pptx
2. Linear regression with one variable.pptx2. Linear regression with one variable.pptx
2. Linear regression with one variable.pptx
 
Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1
 
algo_vc_lecture8.ppt
algo_vc_lecture8.pptalgo_vc_lecture8.ppt
algo_vc_lecture8.ppt
 
Implementing an 8-chip game based on the A algorithm.pptx
Implementing an 8-chip game based on the A algorithm.pptxImplementing an 8-chip game based on the A algorithm.pptx
Implementing an 8-chip game based on the A algorithm.pptx
 
(Slides) Efficient Evaluation Methods of Elementary Functions Suitable for SI...
(Slides) Efficient Evaluation Methods of Elementary Functions Suitable for SI...(Slides) Efficient Evaluation Methods of Elementary Functions Suitable for SI...
(Slides) Efficient Evaluation Methods of Elementary Functions Suitable for SI...
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Adaptive Parallelization of Queries over Dependent Web Service Calls
Adaptive Parallelization of Queries over Dependent Web Service CallsAdaptive Parallelization of Queries over Dependent Web Service Calls
Adaptive Parallelization of Queries over Dependent Web Service Calls
 
Unit 2 Modeling of Programs A function maps inputs to out.docx
Unit 2 Modeling of Programs A function maps inputs to out.docxUnit 2 Modeling of Programs A function maps inputs to out.docx
Unit 2 Modeling of Programs A function maps inputs to out.docx
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
 
M2-Recursion.pptx
M2-Recursion.pptxM2-Recursion.pptx
M2-Recursion.pptx
 

More from Rajendran

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

More from Rajendran (20)

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

Recently uploaded

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 

recursive problem_solving

  • 1. 4.3 Recursive problem solving In the previous section, we used functional composition to break a problem into two procedures that can be composed to produce the desired output. A particularly useful variation on this is when we can break a problem into a smaller version of the original problem. The goal is to be able to feed the output of one application of the procedure back into the same procedure as its input for the next application, as shown inFigure 4.3. Fig ure 4.3: Circular Composition. Here’s a corresponding Scheme procedure: (define f (lambda (n) (f n)))
  • 2. Of course, this doesn’t work very well!1 Every application of f results in another application of f to evaluate. This never stops — no output is ever produced and the interpreter will keep evaluating applications of f until it is stopped or runs out of memory. We need a way to make progress and eventually stop, instead of going around in circles. To make progress, each subsequent application should have a smallerinput. Then, the applications stop when the input to the procedure is simple enough that the output is already known. The stopping condition is called thebase case, similarly to the grammar rules in Section 2.4. In our grammar examples, the base case involved replacing the nonterminal with nothing (e.g.,MoreDigits ::⇒⇒ ϵϵ) or with a terminal (e.g., Noun ::⇒⇒ Alice). In recursive procedures, the base case will provide a solution for some input for which the problem is so simple we already know the answer. When the input is a number, this is often (but not necessarily) when the input is 0 or 1. To define a recursive procedure, we use an if expression to test if the input matches the base case input. If it does, the consequent expression is the known answer for the base case. Otherwise, the recursive case applies the procedure again but with a smaller input.
  • 3. That application needs to make progress towards reaching the base case. This means, the input has to change in a way that gets closer to the base case input. If the base case is for 0, and the original input is a positive number, one way to get closer to the base case input is to subtract 1 from the input value with each recursive application. This evaluation spiral is depicted in Figure 4.4. With each subsequent recursive call, the input gets smaller, eventually reaching the base case. For the base case application, a result is returned to the previous application. This is passed back up the spiral to produce the final output. Keeping track of where we are in a recursive evaluation is similar to keeping track of the subnetworks in an RTN traversal. The evaluator needs to keep track of where to return after each recursive evaluation completes, similarly to how we needed to keep track of the stack of subnetworks to know how to proceed in an RTN traversal.
  • 4. Fig ure 4.4: Recursive Composition. Here is the corresponding procedure: (define g (lambda (n) (if (= n 0) 1 (g (- n 1))))) Unlike the earlier circular f procedure, if we apply g to any non-negative integer it will eventually produce an output. For example, consider evaluating (g 2). When we evaluate the first application, the value of the parameter n is 2, so the predicate expression (= n 0) evaluates to false and the value of the procedure body is the value of the alternate expression, (g (- n 1)). The subexpression, (- n 1) evaluates to 1, so the result is the result of applying g to 1. As with the previous application, this leads to the application, (g (- n 1)), but this time the value of n is 1, so (- n 1) evaluates to 0. The next application leads to the application, (g 0). This time, the predicate expression evaluates to true and we have reached the base case. The consequent expression is just 1, so no further applications of g are performed and this is the result of the application (g 0).
  • 5. This is returned as the result of the (g 1) application in the previous recursive call, and then as the output of the original (g 2) application. We can think of the recursive evaluation as winding until the base case is reached, and then unwinding the outputs back to the original application. For this procedure, the output is not very interesting: no matter what positive number we apply g to, the eventual result is 1. To solve interesting problems with recursive procedures, we need to accumulate results as the recursive applications wind or unwind.
  • 6. This is returned as the result of the (g 1) application in the previous recursive call, and then as the output of the original (g 2) application. We can think of the recursive evaluation as winding until the base case is reached, and then unwinding the outputs back to the original application. For this procedure, the output is not very interesting: no matter what positive number we apply g to, the eventual result is 1. To solve interesting problems with recursive procedures, we need to accumulate results as the recursive applications wind or unwind.