Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 1321. CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 7 Sept 13th, 2001 Fall Semester.

Similar presentations


Presentation on theme: "CS 1321. CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 7 Sept 13th, 2001 Fall Semester."— Presentation transcript:

1 CS 1321

2 CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 7 Sept 13th, 2001 Fall Semester

3 Today’s Menu I.Administrivia II.Complex Data Definitions The Data Definition The Template III.Self-referential Data Structures The List Playing with Lists Data Analysis and Template

4 Administrivia Your First Test is coming up soon. It will be held in recitation. Material that will be covered…everything through this week.

5 Announcements Re: The upcoming test. You will have to be familiar with the template portion of the skeleton, and structures in general. At some point, Dave D. will write a practice test; see.announce. Student who studies structures Student who failed to study structures compare

6 Warning We’re 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

7 Concept I (cons cells)

8 Creating Complex Data Definitions Up until now, we’ve 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 isn’t the important part. It’s the comment below that specifies EXACTLY what a posn is. ;; a posn is a structure

9 It is feasible to create data definitions that are more loosely defined: A flim-flam is either: 1.a number, or 2.a symbol, or 3.a posn A more realistic example would be: A Shape

10 Shapes… For simplicity’s sake, let’s 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

11 Our 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

12 ;; A shape is either: ;; 1. A circle ;; 2. A rectangle ;; 3. A triangle WHERE’S THE (define-struct shape …)? We didn’t 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.

13 Your 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 We’re testing for each type of shape! ;; ((triangle? in-shape) ;; …(triangle-corner1 in-shape)… ;; …(triangle-corner2 in-shape)… ;; …(triangle-corner3 in-shape)…))) ;; ((rectangle? in-shape) ;; …(rectangle-lcorner in-shape)… ;; …(rectangle-width in-shape)… ;; …(rectangle-height in-shape)…) ;; (cond ((circle? in-shape) ;; …(circle-center in-shape)… ;; …(circle-radius in-shape)…) ;;(define (fun-with-shape in-shape)

15 So let’s 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?”

16 An 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? Inside 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?

17 An Example ;; Data Analysis and Definitions (define-struct matryoska-doll (height next-doll)) That much is easy, but here’s the Analysis portion that reveals a problem:

18 An Example ;; Data Analysis and Definitions (define-struct matryoska-doll (height next-doll)) That much is easy, but here’s the Analysis portion that reveals a problem: We know we can say: ; a matryoska-doll is a structure where ; height is a number ; next-doll is a matryoska-doll See the dilemma?

19 An Example ;; Data Analysis and Definitions (define-struct matryoska-doll (height next-doll)) That much is easy, but here’s the Analysis portion that reveals a problem: We know we can say: ; a matryoska-doll is a structure where ; height is a number ; next-doll is a matryoska-doll This is self-referential. When does such a definition ever end?

20 An Example We might work around this by saying that ‘next-doll’ is either a symbol, like ‘end, or it’s 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 Let’s play with some dolls to find out how the structure works.

21 An 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)))

22 An 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))) Let’s look at this closely.

23 An Example We know that a matryoska doll is made of two things: ?

24 An Example We know that a matryoska doll is made of two things: ? height

25 An Example We know that a matryoska doll is made of two things: height The next doll structure or a symbol

26 An Example 10 (make-matryoska-doll 10 (make-matryoska-doll 9 (make-matryoska-doll 8 ‘end))) 9 Another doll structure or symbol 8 ‘end

27 An Example (make-matryoska-doll 10 (make-matryoska-doll 9 (make-matryoska-doll 8 ‘end))) 109 8 ‘end We can visualize this another way, if that helps.

28 Another Example... Everyone’s seen a line at a bank… Let’s ask some questions about them. Welcome to the First National Bank of Dan Please wait for the next available Teller

29 Is an empty line still a line? This is a philosophical question, as well as a computing problem...

30 Is an empty line still a line? Put another way, we ask if there’s a something in nothing. J.P. Sartre contemplatingnothingness 109 8 ‘end Well, nothing is certainly something. We saw this with our matryoska dolls with the symbol ‘end. We have to use something to mean nothing.

31 Is an empty line still a line? Yup. An empty line is still a line. It’s just empty.

32 Can a line have just one person in it? Yes. What’s behind that one person? The empty line, which is still a line

33 So 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?

34 Because a line consists of: 1) The empty line or 2) At least one irritated, ticked off customer and a line behind them.

35 No matter what the size of our line, which customers can the teller deal with? The first customer. That’s 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 ? You’ll see.

36 Let’s translate Lines into Lists! A list is a fairly central computing concept to most of today’s modern languages. In its simplest form, it’s similar to the concept of a line. A line is either: 1.The empty line 2.At least one person and a line behind them. A list is either: 1.The empty list 2.At least one ??? and a list of ???.

37 Let’s translate Lines into Lists! A list is a fairly central computing concept to most of today’s modern languages. In its simplest form, it’s similar to the concept of a line. A line is either: 1.The empty line 2.At least one person and a line of people. A list is either: 1.The empty list 2.At least one ??? and a list of ???. What’s the ??? mean? Lists aren’t limited to one data type!

38 Visually Eggs Milk Sausage Butter Cheese …. The Empty List A List with at least One Item We add more stuff to our list as time goes on.

39 Getting 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:

40 A cons cell is NOT a structure! A cons cell is a much older artifact of Scheme and it’s 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.

41 How to work with Cons Cells… (cons )  Creates cons cells (first )  Accesses the “front” of the cons cell (rest )  Accesses the “back” of the cons cell (cons? )  Tells whether or not the item is a cons cell

42 Further 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.

43 cons Fun with cons (examples in DrScheme)

44 Concept II (recursion)

45 Recursion

46 Definition Recursion (rÎ-kûr-zh-n) n. See Recursion. -- The New Hacker’s Dictionary

47 Recursion Defined function 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.

48 Three Characteristics of Recursion 1. Function calls itself recursively 2. Has some terminating condition 3.Moves “closer” to the terminating condition.

49 Recursion Revisited Example: Let’s sum up the numbers from 1 to n. Example ;(sum-nums 4) should produce ; 10, namely 4 + 3 + 2 + 1

50 Insight 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)) Parameter Variable

51 Insight 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 computer’s memory.

52 Why? 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 Scratch Area for (circle-area 4) function call Parameter: radius. Value: 4

53 Why? 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-ring 5 3) function call Parameter: outer Value: 5 Parameter inner Value: 4 Scratch Area for (area-of-ring 5 3) function call Parameter: outer Value: 5 Parameter inner Value: 4 Scratch Area for (area-of-disk 5) function call Parameter: radius Value: 5 Scratch Area for (area-of-disk 5) function call Parameter: radius Value: 5 One function calls another, resulting in a new frame

54 The Activation Stack (area-of-ring 5 4) outer: 5 inner: 4 All of the accumulated activation stacks are held in a area of computer memory called an “activation stack”. It’s just like a stack of plates in a cafeteria-- the most recently added one is on top, and it’s the one you take first.

55 The Activation Stack (area-of-ring 5 4) outer: 5 inner: 4 Let’s watch as we trace the call to area- of-ring...

56 The Activation Stack (area-of-ring 5 4) outer: 5 inner: 4 (- (area-of-disk 5) (area-of-disk 4) ) 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)

57 The 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-ring 5 4) outer: 5 inner: 4 (- (area-of-disk 5) (area-of-disk 4) ) (area-of-disk 5) radius: 5 (* pi 5)

58 The Activation Stack The computer solves the new function, and then returns a value. (area-of-ring 5 4) outer: 5 inner: 4 (- (area-of-disk 5) (area-of-disk 4) ) (area-of-disk 5) radius: 5 (* pi 5) Returns 78.5

59 The Activation Stack As the stepper in DrScheme has shown you, the value is then substituted into the equation. (area-of-ring 5 4) outer: 5 inner: 4 (- 78.5 (area-of-disk 4) ) (area-of-disk 5) radius: 5 (* pi 5)

60 The 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-ring 5 4) outer: 5 inner: 4 (- 78.5 (area-of-disk 4) ) (area-of-disk 5) radius: 5 (* pi 5)

61 The 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) )

62 The Activation Stack So now another activation record is placed onto our stack. The old original artivation record is still there, it is just on the bottom of the stack. (area-of-ring 5 4) outer: 5 inner: 4 (- 78.5 (area-of-disk 4) ) (area-of-disk 4) radius: 4 (* pi 4)

63 The Activation Stack Our latest function call completes, and its activation record knows where to return the result. -- to our original function… (area-of-ring 5 4) outer: 5 inner: 4 (- 78.5 (area-of-disk 4) ) (area-of-disk 4) radius: 4 (* pi 4) Returns 50.24

64 The 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-ring 5 4) outer: 5 inner: 4 (- 78.5 50.24 ) (area-of-disk 4) radius: 4 (* pi 4)

65 The Activation Stack What remains is solved with simple operations. (area-of-ring 5 4) outer: 5 inner: 4 (- 78.5 50.24 )

66 Disclaimer 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. (There’s not enough room on the slides to draw all the functions.)

67 The Activation Stack Using what we’ve learned about activation stacks, we can make the following assertion about recursion: Each time a function calls itself, a new activation record is made, with unique copies of the parameters

68 Solving 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)

69 Solving 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. That’s the easy case. In fact it’s our termination condition.

70 Solving 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…

71 Solving 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)

72 Solving (define (sum-nums n) (cond [ (= 1 n) 1 ] [ else (+ n (sum-nums (- n 1))) ] )) Does it feel like we didn’t quite actually “do” all the work? It may feel like that until you get used to recursion.

73 Testing It’s not merely enough to interact with the function. We also need the formal tests/examples from the design recipe.

74 Finally ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Data Analysis and Definitions ;; ;; Contract: sum-nums: number --> number ;; Purpose: to return the sum of numbers from 1 to N, ;; where N is a number >= 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)

75 Another Example Let’s 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

76 Another Example Let’s 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?

77 Another Example We can therefore define 5! 5! = 5 * 4! Or more generally: n! = n * (n-1)!, where: n! = 0! returns 1.

78 Another 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.

79 Another Example Solving in Scheme: (define (factorial n) (cond [ (zero? n) 1 ] [ else (* n (factorial (- n 1))) ] ))

80 Tracing Factorial substitution modelstack frame model. There are two techniques for tracing this execution: the substitution model, and the stack frame model. We’ve already seen the stack frame model. Let’s look (briefly) at the substitution model (which is very much like what you’d see in the stepper.)

81 Substitution 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. We’ll see later how to halt this evaluation, when this becomes useful.

82 (define (factorial n) (if (zero? n) 1 (* n (factorial (- n 1))))) Let’s trace this for 4! fact (4) 4 * fact (3) 4 * 3 * fact (2) 4 * 3 * 2 * fact (1) 4 * 3 * 2 * 1 * fact (0) 4 * 3 * 2 * 1 * 1 Example Stack Frame Model

83 Recursion 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

84 Recursion Example - mult Define a function called ‘mult’ that find the multiple of two parameters by using only addition (+) and not multiplication (*).

85 Attempt #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.

86 Attempt #2 Better; variable names are precise. (define (multiply multiplicant multiplier) (cond [(= 1 multiplier) multiplicand] [ else (+ multiplicand (multiply multiplicand (- multiplier 1)))]))

87 Recursion Example - prime Q: Q: Write a function that takes in a single number parameter, and determines if it’s a prime number. (Hint: There’s a “remainder” function that returns the remainder of integer division.) Example of (remainder dividend divisor): (remainder 12 9) ==> 3 In other words, 12/9 is some number, which is thrown away, and the remainder is 3, which is returned.

88 Recursion Example - prime Q: Q: Write a function that takes in a single number parameter, and determines if it’s a prime number. (Hint: There’s a “remainder” function that returns the remainder of integer division.)

89 Recursion Example - prime (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))])) Q: Q: Write a function that takes in a single number parameter, and determines if it’s a prime number. (Hint: There’s a “remainder” function that returns the remainder of integer division.) Use recursion. Assume number > 1.

90 Recursion Example - prime (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))])) Q: Q: Write a function that takes in a single number parameter, and determines if it’s a prime number. (Hint: There’s a “remainder” function that returns the remainder of integer division.) Use recursion. Assume number > 1. Lesson: Lesson: we often create “helper” functions when creating a recursive solution. You can create as many functions are necessary.

91 Example – odd/even A more complicated problem: Have your function figure 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!)

92 false (= n 0) IS-EVEN IS-ODD return (is-odd (- n 1)) return (is-odd (- n 1)) yes no (= n 1) yes no (= n 1) return (is-odd (- n 1)) return (is-odd (- n 1)) yes no (= n 0) yes no true false

93 Example – 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.


Download ppt "CS 1321. CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 7 Sept 13th, 2001 Fall Semester."

Similar presentations


Ads by Google