מבוא מורחב למדעי המחשב בשפת Scheme תרגול 2. 2 Outline Scoping and block structure Recursive and iterative processes Orders of growth.

Slides:



Advertisements
Similar presentations
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Advertisements

מבוא מורחב למדעי המחשב בשפת Scheme תרגול 4. Outline Repeated f Accelerating computations – Fibonacci Let and let* Recursion examples – Palindrome? – Log.
Recursion (define tell-story (lambda () (print ‘’Once upon a time there was a mountain. ‘’) (print ‘’On the mountain, there was a temple. ‘’) (print ‘’In.
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
Fall 2008Programming Development Techniques 1 Topic 3 Linear Recursion and Iteration September 2008.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
6.001 SICP SICP – September Processes, Substitution, Recusion, and Iteration Trevor Darrell 32-D web page:
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 2. Reminder: Recursive algorithm Reduce problem to one or more sub-problems of smaller sizes (linear or tree.
Imperative programming public int factorial (int N){ int F = 1; for(X=N; X>1; X-- ){ F= F*X; } return F; } Functional programming (defun factorial(N) (cond.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 4. Outline High order procedures –Finding Roots –Compose Functions Accelerating Computations –Fibonacci 2.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
Algorithms. Problems, Algorithms, Programs Problem - a well defined task. –Sort a list of numbers. –Find a particular item in a list. –Find a winning.
מבוא מורחב - שיעור 2 1 Lecture 2 - Substitution Model (continued) - Recursion - Block structure and scope (if time permits)
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 3. 2 Outline Let High order procedures.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 14 Recursion.
Recursion in Scheme recursion is the basic means for expressing repetition some recursion is on numbers –factorial –fibonacci some recursion is on structures.
Section Section Summary Recursive Algorithms Proving Recursive Algorithms Correct Recursion and Iteration (not yet included in overheads) Merge.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 4. Outline High order procedures –Finding Roots –Compose Functions Accelerating Computations –Fibonacci 2.
Algorithms Friday 7th Week. Algorithms What is an Algorithm? –A series of precise steps, known to stop eventually, to solve a problem –NOT necessarily.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
Lecture 8. How to Form Recursive relations 1. Recap Asymptotic analysis helps to highlight the order of growth of functions to compare algorithms Common.
CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Chapter 3 (Part 3): Mathematical Reasoning, Induction & Recursion  Recursive Algorithms (3.5)  Program Correctness (3.6)
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 12 Recursion.
Recursive. 2 Recursive Definitions In a recursive definition, an object is defined in terms of itself. We can recursively define sequences, functions.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
מבוא מורחב 1 Review: scheme language things that make up scheme programs: self-evaluating 23, "hello", #t names +, pi combinations (+ 2 3) (* pi 4) special.
1 The Evaluator. 2 Compiler vs. Interpreter Command Processing Unit The Computer Program in Low Level Machine Language Program in High Level Language.
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
CS220 Programming Principles 프로그래밍의 이해 2003 가을학기 Class 2 한 태숙.
1/33 Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
From Lambda Calculus to LISP Functional Programming Academic Year Alessandro Cimatti
Recitation 8 Programming for Engineers in Python.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 3. Outline High order procedures –Finding Roots –Compose Functions Accelerating Computations –Fibonacci 2.
1 Binding names קשירת שמות A occurrence of a name z is bound by the innermost procedure that contains the name and either 1. z is a formal parameter of.
Analyzing Programs: Order of Growth CMSC Introduction to Computer Programming October 11, 2002.
1 Chapter 2 Algorithm Analysis Reading: Chapter 2.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
CS314 – Section 5 Recitation 9
Recursive Algorithms Section 5.4.
CS314 – Section 5 Recitation 10
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Chapter 14: Recursion Starting Out with C++ Early Objects
CS21b: Structure and Interpretation
Lesson #6 Modular Programming and Functions.
Applied Algorithms (Lecture 17) Recursion Fall-23
Algorithm design and Analysis
Your turn (Review) What does a lambda expression return when it is evaluated? the value of a lambda expression is a procedure What three things are in.
Recursion UW CSE 160 Winter 2017
Functional Programming
Recursion Winter 2014 UW CSE 140
Binding names קשירת שמות
Streams, Delayed Evaluation and a Normal Order Interpreter
Lecture 13 - Assignment and the environments model Chapter 3
Recursion UW CSE 160 Winter 2016
Lesson #6 Modular Programming and Functions.
Lecture 2 מבוא מורחב.
Introduction to the Lab
Lecture 2 מבוא מורחב.
Recursion.
Presentation transcript:

מבוא מורחב למדעי המחשב בשפת Scheme תרגול 2

2 Outline Scoping and block structure Recursive and iterative processes Orders of growth

Scoping We have seen two methods to introduce names into a program: –Define form introduces a name associated with a procedure or an expression: (define x 5) (define (f x) (* x x)) –Lambda expression introduces names for formal parameters (define (g a b) (+ a b)) ((lambda(a b) (+ a b)) 2 3) Need rules to interpret names. (define x 5) ((lambda(x)(+ x 1)) x) 3

4 Reminder: Bounded variables A procedure definition binds its formal parameters (their names) These names are called bounded variables. Other variables are free variables (define y 7) (define (foo x) (+ x y)) x is bounded to foo, while y is free

5 Reminder: Scope The set of expressions for which binding defines a name is called a scope of this name A bound variable has its binding function’s body as a scope, and is unknown outside its scope Free variables are known anywhere in the program For variables with the same name and overlapping scopes, the more internal binding overrides the other

Example (define y 7) (define z 5) (define (foo x z) (+ x z y)) Foo binds x and z. x and z are bounded to foo Scope of x and z is the body of foo y is known everywhere, z=5 is only outside foo The meaning of foo will not change if we’ll change the names of its formal parameters. 6

Internal Definitions Can define a name inside the lambda expression (local to this procedure/lambda expression) It’s scope is limited to the rest of the body of the procedure (define (g x) (define a 5) (* x a)) Note: Body of a procedure(lambda expression) can consist of multiple sub-expressions. –The value of the last one is defined to be the value of the procedure 7

Reminder: Block structure Binding/Internal definitions isolate a variable from the rest of the program (limit its scope) Can we isolate procedure from the rest of the program (to limit its scope)? Block structure: defining procedures inside other procedure 8

Example (define (f x) (define (g z) (* z z)) (+ (g x) (g x)) ) (define (h x) (define (g x) (+ x x)) (- (g x) (g x))) ) 9

Why do wee need block structure and scoping? It makes our life easier: –Don’t have to remember which names are already used –Hide away helper procedures to see the overall structure of the program 10

11 Example 2 (define x 3) (define (foo y z) (define (g z x) (+ x y (* 2 z))) (g (+ x z) y)) (foo x 5) z,x y,z

12 Example 2: Cont’d (define x 3) (define (foo y z) (define (g z x) (+ x y (* 2 z))) (g (+ x z) y)) (foo x 5) z,x y,z 22

Reminder: Recursive algorithm Reduce problem to one or more sub-problems of smaller sizes (linear or tree recursion) and solve them recursively Solve the very small sized problems directly Usually some computations are required in order to split problem into sub-problems or /and to combine the results 13

Example 1 Compute f(n)=n! Notice that f(n)=n*f(n-1) if n>1 and f(1)=1; Algorithm: 1.If n=1 return 1 2.Computing factorial for n-1 if n>1 3.Multiply result by n and return 14

Example 2a Compute the average of set of n=2^k numbers –Avg({x 1.. x n })=(x x n )/n Notice that: –Avg({x 1.. x n })=[Avg({x 1.. X n/2 })+Avg({x n/2+1.. x n })]/2 Algorithm 1.If input set size is 1, return the input as its average 2.Divide set into 2 subsets of n/2 if n>1 3.Find an average of each subset 4.Return average of two results 15

Example 2b Compute the average of set of numbers –Avg({x 1.. x n })=(x x n )/n Notice that: –Avg({x 1.. x n })=[x n + (n-1)*Avg({x 1.. X n-1 })]/n Algorithm 1.If input set size is 1, return the input as its average 2.Find average of last n-1 numbers 3.Multiply result by (n-1) add x n and the divide by n 16

Example 3 Find if the number x is a power of 2 F(x)=#t if x=2^n for some n or #f otherwise Notice –F(x)=F(x/2) if x is even, F(x)=#t if x=1 and #f otherwise Algorithms 1.If x is odd return #f, if x=1 return #t 2.Compute and return for x/2 17

Recursive calls Function/procedure that calls to itself called recursive procedure Can’t call to itself every time as have to stop somewhere Recursive algorithms are usually implemented using recursive calls 18

19 The conditional form (cond ( ) ( )... ( ) (else )) (define (abs x) (cond ((> x 0) x) ((= x 0) 0) (else (- x))))

Scheme Examples (define (f n) (if (= n 1) 1 (* n f (- n 1))))) (define (is_pow2 x) (cond ( ((= x 1) #t) ((odd? x) #f) (else (is_pow2 (/ x 2)))) )) 20

Special case of recursive processes No need to do computations after return of recursive call 21 call return val calc call return valreturn same val calcno calc call return same val

22 converting a tail recursive call to an iterative process call calc call return val don’t wait In Scheme, a tail recursive procedure results in an iterative process!

Different Meanings of Recursions 23 Recursive AlgorithmsIterative Algorithms Recursive Scheme Function Recursive ProcessIterative Process Tail Recursion

24 Fibonacci Series Recursive algorithm fib(0) = 0 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) :n > 1 Tree recursion (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2)))))) Iterative algorithm Initialize: a = 1, b = 0 count = n Step: a new = a old + b old b new = a old count = count - 1 Tail Recursion (define (fib n) (define (fib-iter a b count) (if (= count 0) b (fib-iter (+ a b) a (- count 1)))) (fib-iter 1 0 n)) Every element is the sum of its predecessors: 1, 1, 2, 3, 5, 8, 13, 21…

25 Tree Recursion

Implementing loops using tail recursion Usually using helper local function (iterator) Pass loop local variables as an argument (usually includes some sort of counter) Check stopping condition Make initial call with initial state arguments 26

Example(Recursion) Input: Amount of money : $1.50 Output: Number of different ways to construct the amount using coins of 1,2,5,10,15,20,50 cents Assume there is unlimited number of coins of each value 27

28 Counting Change =2x=3x+ 4x=++ 93x

29 Counting Change CC(, { } ) = CC(, { } ) + CC( -, { } )

30 Counting Change (define (count-change amount) (cc amount 6)) (define (cc amount kinds-of-coins) (cond ((= amount 0) ) ((or (< amount 0) (= kinds-of-coins 0)) ) (else (+ (cc ) (cc ))))) (define (first-denomination kinds-of-coins) (cond ((= kinds-of-coins 1) 1) ((= kinds-of-coins 2) 2) ((= kinds-of-coins 3) 5) ((= kinds-of-coins 4) 10) ((= kinds-of-coins 5) 20) ((= kinds-of-coins 6) 50)))) 1 0 amount (- kinds-of-coins 1) (- amount (first-denomination kinds-of-coins)) kinds-of-coins

31 Greatest Common Divisor Given integers a>b  0 gcd(a,0) = a gcd(a,b) = gcd(b, a mod b) By Substitution (gcd 30 21) (gcd 21 9) (gcd 9 3) (gcd 3 0) 3 (define (gcd a b) (if (= b 0) a (gcd b (remainder a b))))