Function Definition by Cases and Recursion Lecture 2, Programmeringsteknik del A.

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

Copyright © Cengage Learning. All rights reserved. 6 Equations and Formulas.
Algebra Problems… Solutions Algebra Problems… Solutions © 2007 Herbert I. Gross Set 13 By Herbert I. Gross and Richard A. Medeiros next.
1 Chapter Six Algorithms. 2 Algorithms An algorithm is an abstract strategy for solving a problem and is often expressed in English A function is the.
Factoring Polynomials
Algebra Problems… Solutions Algebra Problems… Solutions © 2007 Herbert I. Gross Set 22 By Herbert I. Gross and Richard A. Medeiros next.
Tirgul 10 Rehearsal about Universal Hashing Solving two problems from theoretical exercises: –T2 q. 1 –T3 q. 2.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
CS 536 Spring Global Optimizations Lecture 23.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
4/25/08Prof. Hilfinger CS164 Lecture 371 Global Optimization Lecture 37 (From notes by R. Bodik & G. Necula)
Computer Science 1620 Programming & Problem Solving.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
29-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
Prof. Bodik CS 164 Lecture 16, Fall Global Optimization Lecture 16.
Please open your laptops, log in to the MyMathLab course web site, and open Quiz 3.1 IMPORTANT NOTE: If you have time left on your quiz clock after you.
Solving Algebraic Equations
Gateway Quiz Reminders: The next Gateway will be given in class next week or the week after )check your course calendar.) Before then, each student who.
Integers and Introduction to Solving Equations
4 Solving Equations 4.1 Simplifying Expressions and Combining Like Terms 4.2 Addition and Subtraction Properties of Equality 4.3 Multiplication and Division.
Introduction While it may not be efficient to write out the justification for each step when solving equations, it is important to remember that the properties.
True or False Unit 3 Lesson 7 Building Blocks of Decision Making With Additions & Modifications by Mr. Dave Clausen True or False.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
Tuples and Lists Lecture 3, Programmeringsteknik del A.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Variables Tutorial 3c variable A variable is any symbol that can be replaced with a number to solve a math problem. An open sentence has at least one.
Copyright © Cengage Learning. All rights reserved. 4 Quadratic Functions.
Open Sentences.
Solving Linear Equations To Solve an Equation means... To isolate the variable having a coefficient of 1 on one side of the equation. Examples x = 5.
CPS120: Introduction to Computer Science Operations Lecture 9.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Testing Abstract Data Structures with QuickCheck Thomas Arts Quviq AB / Chalmers.
You walk directly east from your house one block. How far from your house are you? 1 block You walk directly west from your house one block. How far from.
More on Correctness. Prime Factorization Problem: Write a program that computes all the prime factors of a given number Solution (Idea): Factors are less.
Chapter 2 Inequalities. Lesson 2-1 Graphing and Writing Inequalities INEQUALITY – a statement that two quantities are not equal. SOLUTION OF AN INEQUALITY.
Lesson 1.4 Equations and Inequalities Goal: To learn how to solve equations and check solutions of equations and inequalities.
1/32 This Lecture Substitution model An example using the substitution model Designing recursive procedures Designing iterative procedures Proving that.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Copyright © Cengage Learning. All rights reserved. CHAPTER 4 ELEMENTARY NUMBER THEORY AND METHODS OF PROOF ELEMENTARY NUMBER THEORY AND METHODS OF PROOF.
Copyright © Cengage Learning. All rights reserved. CHAPTER 8 RELATIONS.
Gateway Quiz Reminders: The next Gateway will be given in class next week (check your course calendar.) Before then, each student who did not score 8/8.
Algebra Problems… Solutions Algebra Problems… Solutions © 2007 Herbert I. Gross Set 16 By Herbert I. Gross and Richard A. Medeiros next.
Warm Up Solve. 1. x + 5 = 9 2. x – 34 = 72 = x – 39 x = 4 x = 106
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
SOFTWARE TESTING LECTURE 9. OBSERVATIONS ABOUT TESTING “ Testing is the process of executing a program with the intention of finding errors. ” – Myers.
The Relation Induced by a Partition
Solving systems of equations
Solving Equations with the Variable on Each Side
Intro to C Tutorial 4: Arithmetic and Logical expressions
Introduction to Variables, Algebraic Expressions, and Equations
Direct Proof and Counterexample V: Floor and Ceiling
Recursion 12-Nov-18.
Recursion 2-Dec-18.
Recursion 2-Dec-18.
This Lecture Substitution model
Recursion 29-Dec-18.
Chapter 6 Section 5.
This Lecture Substitution model
Recursion 23-Apr-19.
This Lecture Substitution model
Presentation transcript:

Function Definition by Cases and Recursion Lecture 2, Programmeringsteknik del A

Definitions Revisited A definition double :: Int -> Int double x = 2*x makes a true statement about the function defined, (whatever x is, then double x and 2*x are equal) gives a way of computing calls of the function.

Quiz Given the definition x :: Int x*x = 4 Is x equal to 2?

Quiz Given the definition x :: Int x*x = 4 Is x equal to 2? NO! This is not a valid Haskell definition. It makes a true statement about x, but it does not give a way of computing x.

Computing with Definitions A function call is computed by replacing the call with a copy of the right hand side, with the argument names replaced by the actual arguments. double :: Int -> Int double x = 2*x double 82*8 16

Evaluation Order double (3+5) There may be more than one way to evaluate an expression: double 8 2*(3+5) 2*816 You can use any order of evaluation; they all give the same result. Haskell chooses a suitable one; you don’t need to know which.

Sharing Evaluation double :: Int -> Int double x = x+x double (3*5) double (3*5)+(3*5) 15+(3*5) 30 Is it more work to evaluate the expression in this order?

Sharing Evaluation double :: Int -> Int double x = x+x double (3*5) double (3*5)+(3*5) 30 NO! Haskell `remembers´ that both occurrences of 3*5 are really the same, and evaluates both in one step.

Definition by Cases Often programs must make decisions, and compute different results in different cases. Example:Define max x y to return the maximum of its two arguments. If x <= y, then max x y should be y. If x>y, then max x y should be x.

The Type of Booleans We make a decision by asking: does a condition hold? (e.g. Does x<=y hold?) A condition is either true or false: this is a piece of data, a value! We introduce a new basic type with two values, named after the mathematician George Boole: True, False :: Bool Constants begin with a capital letter.

Some Operators Producing Booleans 2 <= 3True 2 > 3False 2 < 3True 2 == 3False 2 /= 3True Note two equals signs, to avoid confusion with a definition. Not equals.

Functions Returning Booleans Functions can return boolean results (or any other type). Example: inOrder :: Int -> Int -> Int -> Bool inOrder x y z = x <= y && y <= z a && b is True if both a and b are True.

Using Booleans to Define Functions by Cases max :: Int -> Int -> Int max x y | x <= y = y max x y | x > y = x OR max :: Int -> Int -> Int max x y | x <= y = y | x > y = x A guard: an expression of type Bool. If the guard is True, the equation applies.

Evaluation with Guards To evaluate a function call, evaluate each guard in turn until one is True, replace the call with a copy of the right hand side following the true guard. max :: Int -> Int -> Int max x y | x <= y = y | x > y = x max 4 2 ?? 4 <= 2False ?? 4 > 2True 4

Is max Correct? Programming is a very error prone process; programs are rarely correct `first time´. A large part of the cost of software development goes on finding and correcting errors. It is essential to test software: try it on a variety of inputs and see if the output is correct.

Choosing Test Data Test data should be chosen carefully, to include `difficult´ cases that might induce a failure. The max function should be tested at least with x y, and probably combinations of positive and negative arguments. Choose enough test examples so that every case in your program is used at least once!

Dijkstra on Testing ”Testing can never demonstrate the absence of errors in software, only their presence” Edsger W. Dijkstra (but it is very good at the latter).

Specifications What do we mean by `max is correct´? A specification formulates properties we expect max to satisfy. Property:x <= max x y Property:y <= max x y

Why Formulate Specifications? Helps us clarify what max is supposed to do. Can help in testing. Enables us to prove programs correct.

Specifications and Testing We can define function to check whether properties hold. prop_Max :: Int -> Int -> Bool prop_Max x y = x <= max x y && y <= max x y If prop_Max always returns True, then the specification is satisfied. We can test max on many inputs without needing to inspect the results by hand.

Testing with QuickCheck QuickCheck is a tool to help you test your programs. Main> quickCheck prop_Max OK, passed 100 tests quickCheck generates random values to test your property thoroughly.

Testing with QuickCheck (2) What if we make a mistake? max x y | x <= y = x | x > y = y Main> quickCheck prop_Max Falsifiable, after 0 tests 1 0

Specifications and Proofs From the definition of max: x max x y = y x > y==> max x y = x Theorem: x <= max x y Proof:Consider two cases: Case x <= y:y = max x y, so x <= max x y. Case x > y:max x y = x and x <= x, so x <= max x y.

Formal Methods Proofs are costly and also error-prone, but can guarantee correctness. Thorough testing is the most common method today. Customers for safety critical software demand proofs today. Proofs of correctness will play a growing role, thanks to automatic tools to help with proving, demand for better quality software.

Quiz Define abs x to return the absolute value of x (e.g. abs 2 = 2, abs (-3) = 3. sign x to return 1 if x is positive, and -1 if x is negative. State (and prove?) a property relating abs and sign.

Quiz Answer abs x | x <= 0 = -x | x > 0 = x sign x | x < 0 = -1 | x > 0 = 1 | x == 0 = 0 Property: x == sign x * abs x Did you consider this case? This can also be written sign 0 = 0

Recursion Problem:define fac :: Int -> Int fac n = 1 * 2 * … * n What if we already know the value of fac (n-1)? Thenfac n= 1 * 2 * … * (n-1) * n = fac (n-1) * n

A Table of Factorials nfac n Must start somewhere: we know that fac 0 = 1. So fac 1 = 1 * 1. So fac 2 = 1 * 2. So fac 3 = 2 * 3.

A Recursive Definition of Factorial fac :: Int -> Int fac 0 = 1 fac n | n > 0 = fac (n-1) * n Base case. Recursive case.

Evaluating Factorials fac :: Int -> Int fac 0 = 1 fac n | n > 0 = fac (n-1) * n fac 4 ?? 4 == 0False ?? 4 > 0True fac (4-1) * 4 fac 3 * 4 fac 2 * 3 * 4 fac 1 * 2 * 3 * 4 fac 0 * 1 * 2 * 3 * 4 1 * 1 * 2 * 3 * 4 24

There is No Magic! What if we define fac :: Int -> Int fac n = div (fac (n+1)) (n+1) ? fac 4div (fac 5) 5 div (div (fac 6) 6) 5 div (div (div (fac 7) 7) 6) 5... A true statement. Not a useful definition.

Primitive Recursion Define f n in terms of f (n-1), for n > 0. f 0 separately. What if I already know the value of f (n-1)? Can I compute f n from it?

Quiz Define a function power so that power x n == x * x * … * x n times (Of course, power x n == x^n, but you should define power without using ^).

Quiz Define a function power so that power x n == x * x * … * x n times power x 0 = 1 power x n | n > 0 = power x (n-1) * x Don’t forget the base case! Since this equals (x * x * … * x) * x n-1 times

General Recursion What if I know the values of f x for all x less than n? Can I compute f n from them? Example x^(2*n) == (x*x)^n x^(2*n+1) == (x*x)^n * x

Power Using General Recursion power :: Int -> Int -> Int power x 0 = 1 power x n | n `mod` 2 == 0= power (x*x) (n `div` 2) | n `mod` 2 == 1= power (x*x) (n `div` 2) * x Base case is still needed. Two recursive cases. Why might this definition of power be preferred?

Comparing the Versions First Version power 3 5 power 3 4 * 3 power 3 3 * 3 * 3 power 3 2 * 3 * 3 * 3 power 3 1 * 3 * 3 * 3 * 3 power 3 0 * 3 * 3 * 3 * 3 * 3 1 * 3 * 3 * 3 * 3 * Second Version power 3 5 power 9 2 * 3 power 81 1 * 3 power 81 0 * 81 * 3 1 * 81 * function calls, 5 multiplications. 4 function calls, 4 multiplications.

A More Difficult Example Define prime :: Int -> Bool, so that prime n is True if n is a prime number. What if we know whether (n-1) is prime? What if we know whether each smaller number is prime? NO HELP!

Generalise the Problem! n is prime meansNo k in the range 2<=k<n divides n. Generalisation Replace 2 by a variable. Define factors m n == True if Some k in the range m<=k<n divides n. Soprime n = not (factors 2 n) not x is True if x is False, and vice versa.

Recursive Decomposition Problem: Does any k in the range m<=k<n divide n? What if we know whether any k in a smaller range divides n? Some k in the range m<=k<n divides n ifm divides n, orsome k in the range m+1<=k<n divides n.

Recursive Solution factors :: Int -> Int -> Bool factors m n | m == n = False | m < n = divides m n || factors (m+1) n divides :: Int -> Int -> Bool divides m n = n `mod` m == 0 There is no k in the range n<=k<n. x || y is True if x is True or y is True.

What is Getting Smaller? The range m<=k<n contains n-m elements. Call this the problem size. factors m n | m == n = False | m < n = divides m n || factors (m+1) n Base case: n-m == 0 Recursive case: n-(m+1) == (n-m)-1 The problem size gets smaller in each call, until it reaches zero. So recursion terminates.

Lessons Recursion lets us decompose a problem into smaller subproblems of the same kind -- a powerful problem solving tool in any programming language! A more general problem may be easier to solve recursively than a `simpler´ one, because the recursive calls can do more. To ensure termination, define a `problem size´ which must be greater than zero in the recursive cases, and decreases by at least one in each recursive call.