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

Slides:



Advertisements
Similar presentations
SCRATCH Lesson Two – Interactive Concepts Using Sensing, Operators, and Variables.
Advertisements

Introduction to Recursion and Recursive Algorithms
MATH 224 – Discrete Mathematics
CS 206 Introduction to Computer Science II 02 / 27 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 03 / 04 / 2009 Instructor: Michael Eckmann.
Introduction to Computing Science and Programming I
Recursion, pt. 2: Thinking it Through. What is Recursion? Recursion is the idea of solving a problem in terms of solving a smaller instance of the same.
CS 106 Introduction to Computer Science I 11 / 09 / 2007 Instructor: Michael Eckmann.
Computer Science II Recursion Professor: Evan Korth New York University.
Kavita Math231 Recursion and Iteration. Kavita Math231 We use Recursion when we have to perform a complex task that can be broken into the several subtasks.
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
CS 206 Introduction to Computer Science II 10 / 15 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 28 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
CSC 160 Computer Programming for Non-Majors Lecture #7: Variables Revisited Prof. Adam M. Wittenstein
Hashing General idea: Get a large array
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
analysis, plug ‘n’ chug, & induction
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
Simplifying Rational Expressions – Part I
CS CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 5 Sept 4th, 2001 Fall Semester.
Lecture for Week Spring.  Numbers can be represented in many ways. We are familiar with the decimal system since it is most widely used in everyday.
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
1 Decrease-and-Conquer Approach Lecture 06 ITS033 – Programming & Algorithms Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing.
CS CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 11 Sept 27th, 2001 Fall Semester.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
M180: Data Structures & Algorithms in Java
Week 5 - Monday.  What did we talk about last time?  Linked list implementations  Stacks  Queues.
CS 330 Programming Languages 11 / 21 / 2006 Instructor: Michael Eckmann.
Prerequisites: Fundamental Concepts of Algebra
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
CS CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 10 Sept 25th, 2001 Fall Semester.
Cs1321 December 6, 2001 Review. What is computer science? What's an algorithm? Processes and programs Overview of some programming language concepts Functional.
Lecture on Set! And Local CS 2135 Copyright Kathi Fisler, 2002 This material requires Advanced Language Level.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
CS 330 Programming Languages 11 / 15 / 2007 Instructor: Michael Eckmann.
CS CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 6 Sept 6th, 2001 Fall Semester.
CS CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 13 October 4, 2001 Fall Semester.
Sometimes Structural Recursion Isn't Enough CS 5010 Program Design Paradigms “Bootcamp” Lesson 8.1 TexPoint fonts used in EMF. Read the TexPoint manual.
CS CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 16 October 18, 2001 Fall Semester.
Solving Your Problem by Generalization CS 5010 Program Design Paradigms “Bootcamp” Lesson © Mitchell Wand, This work is licensed under.
Real Zeros of Polynomial Functions
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Recursion.
User-Written Functions
Topic: Recursion – Part 2
Introduction to Recursion
Lesson #6 Modular Programming and Functions.
Decrease-and-Conquer Approach
Lesson #6 Modular Programming and Functions.
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
CS 1321.
University of Washington Computer Programming I
Lesson #6 Modular Programming and Functions.
Lesson 2: Building Blocks of Programming
Creativity in Algorithms
Fundamentals of Programming
Theory of Computation Turing Machines.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Solving Your Problem by Generalization
Repetitious operations
Lesson #6 Modular Programming and Functions.
Recursion Taken from notes by Dr. Neil Moore
Announcements Quiz 5 HW6 due October 23
Presentation transcript:

CS 1321

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

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

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

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

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

Concept I (cons cells)

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

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

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

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

;; 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.

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)…)))

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)

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?”

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?

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:

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?

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?

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.

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

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.

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

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

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

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

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

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

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

Is an empty line still a line? Put another way, we ask if there’s a something in nothing. J.P. Sartre contemplatingnothingness ‘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.

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

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

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?

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

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.

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 ???.

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!

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.

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:

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.

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

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.

cons Fun with cons (examples in DrScheme)

Concept II (recursion)

Recursion

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

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.

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

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

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

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.

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

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

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.

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

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)

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)

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

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 ( (area-of-disk 4) ) (area-of-disk 5) radius: 5 (* pi 5)

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 ( (area-of-disk 4) ) (area-of-disk 5) radius: 5 (* pi 5)

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 ( (area-of-disk 4) )

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 ( (area-of-disk 4) ) (area-of-disk 4) radius: 4 (* pi 4)

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 ( (area-of-disk 4) ) (area-of-disk 4) radius: 4 (* pi 4) Returns 50.24

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 ( ) (area-of-disk 4) radius: 4 (* pi 4)

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

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.)

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

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)

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.

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…

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)

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.

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

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)

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

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?

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

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.

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

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.)

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.

(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

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 =

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

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.

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

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.

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.)

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.

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.

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!)

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

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.