SlideShare a Scribd company logo
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 (20)

PDF
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
PPT
lazy evaluation
Rajendran
 
DOCX
Type conversion in c
SHIKHA GAUTAM
 
PPTX
Function Pointer in C
Lakshmi Sarvani Videla
 
PPT
Introduction to C Programming
vampugani
 
PPTX
2 r algebra
Mr Patrick NIYISHAKA
 
PDF
Handout # 4 functions + scopes
NUST Stuff
 
PDF
Functions
Michael Gordon
 
PPT
Model and Design
Dr Shashikant Athawale
 
PDF
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
PDF
Domain and range (linear, quadratic, rational functions)
Rose Mary Tania Arini
 
PDF
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
PPTX
Type casting in c programming
Rumman Ansari
 
PDF
selection structures
Micheal Ogundero
 
PDF
Notes: Verilog Part 1 - Overview - Hierarchical Modeling Concepts - Basics
Jay Baxi
 
PPTX
Highorderfunctions in swift
Ahmet Keskin
 
PDF
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
Muhammad Hammad Waseem
 
PPTX
Lecture 4: Functions
Vivek Bhargav
 
PPTX
Ch6 Loops
SzeChingChen
 
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
lazy evaluation
Rajendran
 
Type conversion in c
SHIKHA GAUTAM
 
Function Pointer in C
Lakshmi Sarvani Videla
 
Introduction to C Programming
vampugani
 
Handout # 4 functions + scopes
NUST Stuff
 
Functions
Michael Gordon
 
Model and Design
Dr Shashikant Athawale
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
Domain and range (linear, quadratic, rational functions)
Rose Mary Tania Arini
 
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
Type casting in c programming
Rumman Ansari
 
selection structures
Micheal Ogundero
 
Notes: Verilog Part 1 - Overview - Hierarchical Modeling Concepts - Basics
Jay Baxi
 
Highorderfunctions in swift
Ahmet Keskin
 
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
Muhammad Hammad Waseem
 
Lecture 4: Functions
Vivek Bhargav
 
Ch6 Loops
SzeChingChen
 

Similar to recursive problem_solving (20)

PPT
Recursion and looping
xcoolanurag
 
DOCX
Ann a Algorithms notes
Prof. Neeta Awasthy
 
PPTX
heuristic technique.pptx...............................
gursharansinghmavi20
 
PPTX
Daa unit 1
jinalgoti
 
DOCX
UNIT-1.docx Design and Analysis of Algorithm
swethajosephsastry
 
PPTX
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
15AnasKhan
 
PDF
DATA STRUCTURE.pdf
ibrahim386946
 
PDF
DATA STRUCTURE
RobinRohit2
 
PPTX
Presentation 1 on algorithm for lab progress
manjudarshan8543
 
PPTX
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
Tanya Makkar
 
PPTX
Recursion | C++ | DSA
Sumit Pandey
 
PPT
DAA-Introduction-Divide and Conquer Technique
sailaja156145
 
PDF
Python_Module_2.pdf
R.K.College of engg & Tech
 
PPTX
2. Linear regression with one variable.pptx
Emad Nabil
 
PDF
Anlysis and design of algorithms part 1
Deepak John
 
PPT
algo_vc_lecture8.ppt
Nehagupta259541
 
PPTX
Implementing an 8-chip game based on the A algorithm.pptx
lwz614595250
 
PPT
(Slides) Efficient Evaluation Methods of Elementary Functions Suitable for SI...
Naoki Shibata
 
PDF
Dynamic programming
Jay Nagar
 
Recursion and looping
xcoolanurag
 
Ann a Algorithms notes
Prof. Neeta Awasthy
 
heuristic technique.pptx...............................
gursharansinghmavi20
 
Daa unit 1
jinalgoti
 
UNIT-1.docx Design and Analysis of Algorithm
swethajosephsastry
 
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
15AnasKhan
 
DATA STRUCTURE.pdf
ibrahim386946
 
DATA STRUCTURE
RobinRohit2
 
Presentation 1 on algorithm for lab progress
manjudarshan8543
 
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
Tanya Makkar
 
Recursion | C++ | DSA
Sumit Pandey
 
DAA-Introduction-Divide and Conquer Technique
sailaja156145
 
Python_Module_2.pdf
R.K.College of engg & Tech
 
2. Linear regression with one variable.pptx
Emad Nabil
 
Anlysis and design of algorithms part 1
Deepak John
 
algo_vc_lecture8.ppt
Nehagupta259541
 
Implementing an 8-chip game based on the A algorithm.pptx
lwz614595250
 
(Slides) Efficient Evaluation Methods of Elementary Functions Suitable for SI...
Naoki Shibata
 
Dynamic programming
Jay Nagar
 
Ad

More from Rajendran (20)

PPT
Element distinctness lower bounds
Rajendran
 
PPT
Scheduling with Startup and Holding Costs
Rajendran
 
PPT
Divide and conquer surfing lower bounds
Rajendran
 
PPT
Red black tree
Rajendran
 
PPT
Hash table
Rajendran
 
PPT
Medians and order statistics
Rajendran
 
PPT
Proof master theorem
Rajendran
 
PPT
Recursion tree method
Rajendran
 
PPT
Recurrence theorem
Rajendran
 
PPT
Master method
Rajendran
 
PPT
Master method theorem
Rajendran
 
PPT
Hash tables
Rajendran
 
PPT
Lower bound
Rajendran
 
PPT
Master method theorem
Rajendran
 
PPT
Greedy algorithms
Rajendran
 
PPT
Longest common subsequences in Algorithm Analysis
Rajendran
 
PPT
Dynamic programming in Algorithm Analysis
Rajendran
 
PPT
Average case Analysis of Quicksort
Rajendran
 
PPT
Np completeness
Rajendran
 
PPT
computer languages
Rajendran
 
Element distinctness lower bounds
Rajendran
 
Scheduling with Startup and Holding Costs
Rajendran
 
Divide and conquer surfing lower bounds
Rajendran
 
Red black tree
Rajendran
 
Hash table
Rajendran
 
Medians and order statistics
Rajendran
 
Proof master theorem
Rajendran
 
Recursion tree method
Rajendran
 
Recurrence theorem
Rajendran
 
Master method
Rajendran
 
Master method theorem
Rajendran
 
Hash tables
Rajendran
 
Lower bound
Rajendran
 
Master method theorem
Rajendran
 
Greedy algorithms
Rajendran
 
Longest common subsequences in Algorithm Analysis
Rajendran
 
Dynamic programming in Algorithm Analysis
Rajendran
 
Average case Analysis of Quicksort
Rajendran
 
Np completeness
Rajendran
 
computer languages
Rajendran
 
Ad

Recently uploaded (20)

PPTX
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PDF
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
CHILD RIGHTS AND PROTECTION QUESTION BANK
Dr Raja Mohammed T
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
PDF
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
Dimensions of Societal Planning in Commonism
StefanMz
 
CHILD RIGHTS AND PROTECTION QUESTION BANK
Dr Raja Mohammed T
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 

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.