Title: CS
11321
2CS1321Introduction to Programming
- Georgia Institute of Technology
- College of Computing
- Lecture 7
- January 29th, 2002
- Spring Semester
3Todays Menu
- Administrivia
- Complex Data Definitions
- The Data Definition
- The Template
- Self-referential Data Structures
- The List
- Playing with Lists
- Data Analysis and Template
4Administrivia
Your First Test is coming up soon. ltinsert drum
rollgt It will be held in recitation. Material
that will be coveredeverything through this
lecture.
5Announcements
Re The upcoming test. You will have to be
familiar with the template portion of the
skeleton, and structures in general. At some
point, we will publish a practice test see
.announce.
compare
6Warning
- Were going to learn two, count em two, key
concepts today. - They might seem unrelated, but in fact they go
together like hotcakes and molasses. - They are lists (or cons cells)
- - and -
- recursion
7Concept
I
(cons cells)
8Creating Complex Data Definitions
Up until now, weve been dealing with very simple
data definitions. For example
(define-struct posn (x y)) a posn is a
structure (make-posn a b) where a and b
are numbers For our Data Definition, the actual
declaration of the structure isnt the important
part. Its the comment below that specifies
EXACTLY what a posn is.
a posn is a structure
9(No Transcript)
10Shapes
For simplicitys sake, lets say that a Shape can
only be
Triangle it has three points
Rectangle it has an upper left-
hand corner, a base, and a height.
Circle it has a center position and
a radius
11Our Data Definitions
(define-struct rectangle (lcorner width
height)) a rectangle is a structure
(make-rectangle lc w h) where lc is a posn, and
w h are numbers (define-struct triangle
(corner1 corner2 corner3)) a triangle is a
structure (make-triangle c1 c2 c3) where c1,
c2, c3 are posns (define-struct circle (center
radius)) a circle is a structure (make-circle
c r) where c is a posn and r is a number
12We didnt need one. A shape is not a structure.
It could be anyone of three structures, in fact.
Which means any function that takes in a
shape needs to be prepared to deal with any of
the three possibilities.
13Your Template
(define (fun-with-shape in-shape) (cond
((circle? in-shape)
(circle-center in-shape)
(circle-radius in-shape))
((rectangle? in-shape)
(rectangle-lcorner in-shape)
(rectangle-width in-shape)
(rectangle-height in-shape))
((triangle? in-shape)
(triangle-corner1 in-shape)
(triangle-corner2 in-shape)
(triangle-corner3 in-shape))))
14(define (fun-with-shape in-shape)
(cond ((circle? in-shape)
(circle-center in-shape)
(circle-radius in-shape))
((rectangle? in-shape)
(rectangle-lcorner in-shape)
(rectangle-width in-shape)
(rectangle-height in-shape))
((triangle? in-shape)
(triangle-corner1 in-shape)
(triangle-corner2 in-shape)
(triangle-corner3 in-shape))))
Were testing for each type of shape!
15So lets build off this idea.
In Scheme, and indeed most programming languages,
there exists an idea of data definitions that
reference themselves within their own definitions.
Which of course causes you the student to ask,
What?
16An Example
We of course are all avid collectors of Russian
Matryoska dolls--you know, those dolls that have
dolls in them, and so on, and so on?
Each doll has its own height, and might contain
another doll. But at some point, the chain comes
to an end. How can this be modeled in Scheme?
17An Example
Data Analysis and Definitions (define-struct
matryoska-doll (height next-doll)) That much is
easy, but heres the Analysis portion that
reveals a problem
18An Example
Data Analysis and Definitions (define-struct
matryoska-doll (height next-doll)) That much is
easy, but heres the Analysis portion that
reveals a problem
See the dilemma?
We know we can say a matryoska-doll is a
structure where height is a number
next-doll is a matryoska-doll
19An Example
Data Analysis and Definitions (define-struct
matryoska-doll (height next-doll)) That much is
easy, but heres the Analysis portion that
reveals a problem
This is self-referential. When does such
a definition ever end?
We know we can say a matryoska-doll is a
structure where height is a number
next-doll is a matryoska-doll
20An Example
We might work around this by saying that
next-doll is either a symbol, like end, or
its a matryoska-doll. Data Analysis and
Definitions (define-struct matryoska-doll (height
next-doll)) a matryoska-doll is a structure
where height is a number next-doll
is either a
matryoska-doll, or the
symbol end
Lets play with some dolls to find out how the
structure works.
21An Example
Data Analysis and Definitions (define-struct
matryoska-doll (height next-doll)) a
matryoska-doll is a structure where height
is a number next-doll is either
a matryoska-doll, or
the symbol end
(make-matryoska-doll 10
(make-matryoska-doll 9
(make-matryoska-doll 8 end)))
22An Example
Data Analysis and Definitions (define-struct
matryoska-doll (height next-doll)) a
matryoska-doll is a structure where height
is a number next-doll is either
a matryoska-doll, or
the symbol end
Lets look at this closely.
(make-matryoska-doll 10
(make-matryoska-doll 9
(make-matryoska-doll 8 end)))
23An Example
We know that a matryoska doll is made of two
things
? ?
24An Example
We know that a matryoska doll is made of two
things
?
height
25An Example
We know that a matryoska doll is made of two
things
The next doll structure or a symbol
height
26An Example
(make-matryoska-doll 10
(make-matryoska-doll 9
(make-matryoska-doll 8 end)))
10
9
Another doll structure or symbol
27An Example
(make-matryoska-doll 10
(make-matryoska-doll 9
(make-matryoska-doll 8 end)))
10
9
8
end
We can visualize this another way, if that helps.
28Another Example...
Everyones seen a line at a bank Lets ask some
questions about them.
29Is an empty line still a line?
This is a philosophical question, as well as a
computing problem...
30Is an empty line still a line?
Put another way, we ask if theres a something in
nothing.
Well, nothing is certainly something. We saw
this with our matryoska dolls with the symbol
end. We have to use something to mean nothing.
J.P. Sartre contemplating nothingness
31Is an empty line still a line?
Yup. An empty line is still a line. Its just
empty.
32Can a line have just one person in it?
Yes.
Whats behind that one person?
The empty line, which is still a line
33So does anything change as more people get in
line?
Not really. As people are added or removed from
a line, we still have a line.
WHY?
34Because a line consists of 1) The empty line
or 2) At least
one irritated, ticked off customer
and a line behind them.
35No matter what the size of our line, which
customers can the teller deal with?
The first customer. Thats all he or she has
access to.
So how does the teller get to the rest of the
line?
By dealing with the first customer.
Why are you highlighting first and rest?
Youll see.
36Lets translate Lines into Lists!
A list is a fairly central computing concept to
most of todays modern languages. In its
simplest form, its similar to the concept of a
line.
- A list is either
- The empty list
- At least one ??? and a list of ???.
- A line is either
- The empty line
- At least one person and a line behind them.
37Lets translate Lines into Lists!
A list is a fairly central computing concept to
most of todays modern languages. In its
simplest form, its similar to the concept of a
line.
Whats the ??? mean? Lists arent limited to one
data type!
- A list is either
- The empty list
- At least one ??? and a list of ???.
- A line is either
- The empty line
- At least one person and a line of people.
38Visually
A List with at least One Item
A List with at least One Item
The Empty List
Eggs
Eggs Milk Sausage Butter Cheese .
We add more stuff to our list as time goes on.
39Getting around Scheme Syntax
The fundamental unit of a List is NOT a
structure, per say. It is the
CONS CELL
A cons cell is a structure that stores two
items of generic types. A visual representation
of a cons cell would be
40A cons cell is NOT a structure!
A cons cell is a much older artifact of Scheme
and its predecessor computer language Lisp.
You do not create a cons cell as you would a
structure. You do not access cons cell data as
you would access data from a structure.
41How to work with Cons Cells
(cons ltitemgt ltitemgt) ? Creates cons cells (first
ltcons cellgt) ? Accesses the front of the
cons cell (rest ltcons cellgt) ? Accesses the
back of the cons cell (cons?
ltitemgt) ? Tells whether or not the item is
a cons cell
42Further Restrictions on Cons Cells
In Beginning through Advanced Scheme Modes,
certain restrictions are placed on cons and
associated functions 1) Cons Cells can ONLY
be used to create lists 2) the
functions first, rest, cons? exist only
in these language levels for readability
purposes. To use them in Full Scheme, you
must define them yourselves from other
functions in Scheme.
43cons
Fun with cons (examples in DrScheme)
44Concept
II
(recursion)
45Recursion
46Definition
Recursion (rÎ-kûr-zh-n) n. See Recursion. --
The New Hackers Dictionary
47Recursion Defined
- Recursion is when a function calls itself.
- Powerful mechanism for repetition.
- Makes algorithms more compact and simple.
- Function calls a clone of itself.
- Very useful, especially for dynamic data types.
48Three Characteristics of Recursion
- 1. Function calls itself recursively
- 2. Has some terminating condition
- Moves closer to the terminatingcondition.
Know this!!!
49Recursion Revisited
Example Lets sum up the numbers from 1 to
n. Example (sum-nums 4) should produce
10, namely 4 3 2 1
50Insight
In order to understand how to solve this, we need
an additional insight. We already know about
variables, and the special flavor of variables
called parameters (define pi
3.14) (define (circle-area
radius) ( radius radius pi))
51Insight
We also know that we cannot refer to a parameter
outside of a function. Once the function is no
longer running, basically the parameter
disappears from the computers memory.
52Why?
As it turns out, each time you call a function,
the computer creates a scratch work area. Each
time the function completes, the work area is
disposed. Any values you want to save must be
returned. (circle-area 4) We call this
work area the activation frame
Scratch Area for (circle-area 4) function
call Parameter radius. Value 4
53Why?
If a function calls another function, another
activation frame is made, and the computer
remembers where it left off so it can
return. (area-of-ring 5 3)
Scratch Area for (area-of-disk 5) function
call Parameter radius Value 5
Scratch Area for (area-of-ring 5 3) function
call Parameter outer Value 5 Parameter
inner Value 4
One function calls another, resulting in a
new frame
54The Activation Stack
All of the accumulated activation stacks are held
in a area of computer memory called an
activation stack. Its just like a stack of
plates in a cafeteria-- the most recently added
one is on top, and its the one you take first.
(area-of-ring 5 4) outer 5 inner 4
55The Activation Stack
Lets watch as we trace the call to
area-of-ring...
(area-of-ring 5 4) outer 5 inner 4
56The Activation Stack
We know that (area-of-ring 5 4) is the same
as (- (area-of-disk 5) (area-of-disk 4)
) So we have to first solve for (area-of-disk
5)
(area-of-ring 5 4) outer 5 inner 4 (-
(area-of-disk 5) (area-of-disk 4) )
57The Activation Stack
We know that (area-of-ring 5 4) is the same
as (- (area-of-disk 5) (area-of-disk 4)
) So we have to first solve for (area-of-disk
5) This creates a new activation frame...
(area-of-disk 5) radius 5 ( pi 5)
(area-of-ring 5 4) outer 5 inner 4 (-
(area-of-disk 5) (area-of-disk 4) )
58The Activation Stack
The computer solves the new function, and then
returns a value.
(area-of-disk 5) radius 5 ( pi 5)
Returns 78.5
(area-of-ring 5 4) outer 5 inner 4 (-
(area-of-disk 5) (area-of-disk 4) )
59The Activation Stack
As the stepper in DrScheme has shown you, the
value is then substituted into the equation.
(area-of-disk 5) radius 5 ( pi 5)
(area-of-ring 5 4) outer 5 inner 4 (- 78.5
(area-of-disk 4) )
60The Activation Stack
But what happens to the old activation
record? It was just a scratch area, and the
computer reclaims the memory. That one
activation record is no longer needed.
(area-of-disk 5) radius 5 ( pi 5)
(area-of-ring 5 4) outer 5 inner 4 (- 78.5
(area-of-disk 4) )
61The Activation Stack
So we are now left with the original function
but the other half of the equation requires that
we solve area-of-disk area, this time using 4
(area-of-ring 5 4) outer 5 inner 4 (- 78.5
(area-of-disk 4) )
62The Activation Stack
So now another activation record is placed onto
our stack. The old original activation record is
still there, it is just on the bottom of the
stack.
(area-of-disk 4) radius 4 ( pi 4)
(area-of-ring 5 4) outer 5 inner 4 (- 78.5
(area-of-disk 4) )
63The Activation Stack
Our latest function call completes, and its
activation record knows where to return the
result. -- to our original function
(area-of-disk 4) radius 4 ( pi 4)
Returns 50.24
(area-of-ring 5 4) outer 5 inner 4 (- 78.5
(area-of-disk 4) )
64The Activation Stack
The substitution is made (we can confirm this
with the stepper), and we then remove the top
activation record. The top activation record can
go away.
(area-of-disk 4) radius 4 ( pi 4)
(area-of-ring 5 4) outer 5 inner 4 (- 78.5
50.24 )
65The Activation Stack
What remains is solved with simple operations.
(area-of-ring 5 4) outer 5 inner 4 (- 78.5
50.24 )
66Disclaimer
Alert students will note that common operations
like , - used in this example are themselves
functions.
We purposefully did not draw activation records
of these functions, but could have nonetheless.
(Theres not enough room on the slides to draw
all the functions.)
67The Activation Stack
Using what weve learned about activation stacks,
we can make the following assertion about
recursion
68Solving
Back to our original exercise Sum the numbers
from 1 to n. We know that the function will take
the form (define (sum-nums n)
69Solving
Back to our original exercise Sum the numbers
from 1 to N. We know that the function will take
the form (define (sum-nums n) (cond
( 1 n) 1
The first possibility is that the number is 1.
Thats the easy case. In fact its our
termination condition.
70Solving
Back to our original exercise Sum the numbers
from 1 to N. We know that the function will take
the form (define (sum-nums n) (cond
( 1 n) 1 else
(??????
The next possibility is that the number is not
1. In that case, return what? Any ideas??? Hint
we want to use this recursion idea and this
implies we will make just a SMALL step toward Our
ultimate answer
71Solving
Back to our original exercise Sum the numbers
from 1 to N. We know that the function will take
the form (define (sum-nums n) (cond
( 1 n) 1 else
( n (sum-nums (- n 1))) ))
The next possibility is that the number is not
1. In that case, return n plus (sum-nums (- n 1)
72Solving
(define (sum-nums n) (cond ( 1 n) 1
else ( n
(sum-nums (- n 1))) ))
Does it feel like we didnt quite actually do
all the work? It may feel like that until you get
used to recursion.
73Testing
Its not merely enough to interact with the
function. We also need the formal tests/examples
from the design recipe.
74Finally
lt1gt Data
Analysis and Definitions ltnot requiredgt
Contract sum-nums number --gt number Purpose
to return the sum of numbers from 1 to N,
where N is a number gt 1 Examples
(sum-nums 4) should return 10 (sum-nums 1)
should return 1 (sum-nums 10) should return
55 Definition (define (sum-nums n) (cond
( 1 n) 1 else ( n (sum-nums
(- n 1))) )) Tests ( (sum-nums 4) 10) (
(sum-nums 1) 1) ( (sum-nums 10) 55)
75Another Example
Lets also solve factorial using recursion. We
know that 5! is the same as 5 4
3 2 1 We also know that 4! is the same
as 4 3 2 1
76Another Example
Lets also solve factorial using recursion. We
know that 5! is the same as 5 4
3 2 1 We also know that 4! is the same
as 4 3 2 1
See the pattern here?
77Another Example
We can therefore define 5! 5! 5
4! Or more generally n! n
(n-1)!, where
n! 0! returns 1.
78Another Example
We can therefore define 5! 5! 5
4! Or more generally n! n
(n-1)!, where
n! 0! returns 1.
So this is basically what we will code in
Scheme We rely on the recursion to help with
calculating the final answer.
79Another Example
Solving in Scheme
(define (factorial n) (cond (zero? n)
1 else ( n (factorial (- n 1))) ))
80Tracing Factorial
There are two techniques for tracing this
execution the substitution model, and the stack
frame model. Weve already seen the stack frame
model. Lets look (briefly) at the substitution
model (which is very much like what youd see in
the stepper.)
81Substitution Model of Evaluation
(factorial 3) ( 3 (factorial 2)) ( 3 ( 2
(factorial 1))) ( 3 ( 2 ( 1 (factorial
0)))) ( 3 ( 2 ( 1 1))) ( 3 ( 2 1)) ( 3 2) 6
Each argument is evaluated and
substituted. Well see later how to halt this
evaluation, when this becomes useful.
82Stack Frame Model
Example
(define (factorial n) (if (zero? n) 1
( n (factorial (- n 1)))))
Lets trace this for 4!
83Recursion Exercise - mult
Define a function called mult that find the
multiple of two parameters by using only addition
() and not multiplication ().
Thus 5 3 5 5 5
84Recursion Example - mult
Define a function called mult that find the
multiple of two parameters by using only addition
() and not multiplication ().
lt draw flow chart on board gt
85Attempt 1
(define (mult num1 num2) (cond ( 1 num2)
num1 else ( num1 (mult
num1 (- num2 1)))))
Looks ok, but we have some non-descriptive
variable names.
86Attempt 2
(define (multiply multiplicand multiplier)
(cond ( 1 multiplier) multiplicand
else ( multiplicand (multiply
multiplicand (- multiplier
1)))))
Better variable names are precise.
87Recursion Example - prime
Q Write a function that takes in a single
number parameter, and determines if its a prime
number. (Hint Theres a remainder function
that returns the remainder of integer
division.) Example of (remainder dividend
divisor) (remainder 12 9) gt 3 In other
words, 12/9 is some number, which is thrown away,
and the remainder is 3, which is returned.
88Recursion Example - prime
Q Write a function that takes in a single
number parameter, and determines if its a prime
number. (Hint Theres a remainder function
that returns the remainder of integer
division.) lt draw flow chart on board gt
89Recursion Example - prime
Q Write a function that takes in a single
number parameter, and determines if its a prime
number. (Hint Theres a remainder function
that returns the remainder of integer division.)
Use recursion. Assume number gt 1.
(define (prime? num) (prime-helper num (- num
1))) (define (prime-helper num factor) (cond
( 0 (remainder num factor)) ( 1 factor)
else (prime-helper num (- factor 1))))
90Recursion Example - prime
Q Write a function that takes in a single
number parameter, and determines if its a prime
number. (Hint Theres a remainder function
that returns the remainder of integer division.)
Use recursion. Assume number gt 1.
Lesson we often create helper functions
when creating a recursive solution. You can
create as many functions are necessary.
(define (prime? num) (prime-helper num (- num
1))) (define (prime-helper num factor) (cond
( 0 (remainder num factor)) ( 1 factor)
else (prime-helper num (- factor 1))))
91Example odd/even
A more complicated problem Define functions
is-odd and is-even that determine if a number
is odd or even. Have your function figure this
out recursively. (Note odd? and even? are
predefined in scheme, so we will not use them.
We are writing our own!)
92IS-ODD
IS-EVEN
( n 0)
( n 1)
yes
yes
true
true
no
no
( n 1)
( n 0)
yes
yes
false
false
no
no
return (is-odd (- n 1))
return (is-odd (- n 1))
93Example odd/even
A (poor) implementation of the second question
is
(define (is-odd n) (cond ( 1 n) true
( 0 n) false else (is-even (- n
1)))) (define (is-even n) (cond ( 0 n)
true ( 1 n) false else
(is-odd (- n 1))))
We could use (remainder n 2) instead, and get
back 1 or 0. But this way shows a technique
known as mutual recursion.
94Questions?
95(No Transcript)