Chapter 3 Programming with Recursion
|
|
- Percival Mason
- 6 years ago
- Views:
Transcription
1 Plan Chapter 3 Programming with Recursion 1. Examples Correctness Construction methodology Forms of recursion Sven-Olof Nyström/IT Dept/Uppsala University FP 3.1
2 3.1. Examples 3.1. Examples Factorial (revisited from Section 2.13) Program (fact.sml) fun fact n = if n < 0 then error "fact: negative argument" else if n = 0 then 1 else n fact (n 1) Useless test of the error case at each recursive call! Hence we introduce an auxiliary function, and can then use pattern matching in its declaration: fun factaux 0 = 1 factaux n = n factaux (n 1) fun fact1 n = if n < 0 then error "fact1: negative argument" else factaux n In fact1: pre-condition verification (defensive programming) In factaux: no pre-condition verification Sven-Olof Nyström/IT Dept/Uppsala University FP 3.2
3 3.1. Examples Exponentiation Specification function expo x n TYPE: real int real PRE: n 0 POST: x n Construction Error case: n < 0: produce an error message Base case: n = 0 : return 1 General case: n > 0 : return x n = x x n 1 = x expo x (n 1) Program (expo.sml) fun expoaux x 0 = 1.0 expoaux x n = x expoaux x (n 1) fun expo x n = if n < 0 then error "expo: negative argument" else expoaux x n Sven-Olof Nyström/IT Dept/Uppsala University FP 3.3
4 3.1. Examples Triangle Specification function triangle a b TYPE: int int int PRE: (none) POST: i a i b Construction Base case: a > b : return 0 General case: a b : return a i b i = a + a+1 i b i = a + triangle (a+1) b Program (triangle.sml) fun triangle a b = if a > b then 0 else a + triangle (a+1) b Sven-Olof Nyström/IT Dept/Uppsala University FP 3.4
5 3.2. Correctness 3.2. Correctness How do we know that a recursive program computes what we want? Lets try a very simple program. fun f n = if n = 0 then 0 else 1 + f(n-1) What does f compute? Sven-Olof Nyström/IT Dept/Uppsala University FP 3.5
6 3.2. Correctness Correctness (cont) What does this function compute? fun f n = if n = 0 then 0 else 1 + f(n-1) Answer: f n = n, if n>=0 Seems reasonable, but how do we prove it? Sven-Olof Nyström/IT Dept/Uppsala University FP 3.6
7 3.2. Correctness Proof by induction For all n >= 0, f(n) = n. Base case: n = 0. f(n) = 0 = n follows immediately. Induction step: Hypothesis: f(k) = k, for all k such that 0 <= k < n We have f(n) = 1 + f(n 1), by definition 1 + f(n 1) = 1 + (n 1), by induction hypothesis 1 + (n 1) = n, by algebraic transformations Thus f(n) = n It follows that f(n) = n, for all n >= 0. Question: What can we say about f( 1)? Sven-Olof Nyström/IT Dept/Uppsala University FP 3.7
8 3.2. Correctness Another example, slightly harder What does this function compute? fun g(0) = 0 g(n) = n + g(n-1) Sven-Olof Nyström/IT Dept/Uppsala University FP 3.8
9 3.2. Correctness Another example (cont) What does this function compute? fun g(0) = 0 g(n) = n + g(n-1) Answer: g(n) = (n n + n)/2 Proof by induction. For all n >= 0, g(n) = (n n + n)/2 Base case: n = 0. g(n) = (n n + n)/2 by definition (n n + n)/2 = ( )/2 = 0 Induction step Hypothesis: g(k) = (k k + k)/2, for all k such that 0 <= k < n We have g(n) = n + g(n 1), by definition = n + ((n 1) (n 1) + (n 1))/2, by induction hypothesis = n + (n n 2 n n 1)/2, by algebraic transformations = n + (n n n)/2 n, simplification = (n n + n)/2 Thus g(n) = (n n + n)/2 It follows that g(n) = (n n + n)/2, for all n >= 0. Sven-Olof Nyström/IT Dept/Uppsala University FP 3.9
10 3.2. Correctness If you think these examples where too simple Exercises: Prove that the factorial given earlier produces the intended results. Prove the same for the gcd function. What do the functions below compute? Make an educated guess (try on an SML system if you like) and show by induction that your guess was correct. fun h(n) = if n = 0 then 0 else h(n-1)+2*n-1; fun m(a,b) = if a = 0 then 0 else b+m(a-1,b); Sven-Olof Nyström/IT Dept/Uppsala University FP 3.10
11 3.2. Correctness Correctness of functional programs Suppose we have a recursive function fun f(x) =... f(..)... and we want to show that it satisfies some property P(x, f(x)) Solution: Show that the function terminates (for all values of x that we are interested in) Assume that all recursive calls satisfy the property P(...,f(...)). Show P(x, f(x)). Then we have shown that P(x, f(x)) holds for all values of x we are interested in. (This is just an induction proof in disguise.) (By the way, showing that if an answer is returned it will be correct is also known as partial correctness.) Sven-Olof Nyström/IT Dept/Uppsala University FP 3.11
12 3.2. Correctness Example (factorial): fun fac(x) = if x = 0 then 1 else x*fac(x-1) Assume that fac(x) terminates for all x >= 0. Show that P(x,fac(x)) <=> fac(x) = x holds. Assuming property holds for recursive calls... By the definition of the function fac we have fac(x) = if x = 1 then 0 else x ( (x 1)) For x = 0 the property is obvious. For x <> 0 we prove the property by algebraic manipulations. Sven-Olof Nyström/IT Dept/Uppsala University FP 3.12
13 3.3. Construction methodology 3.3. Construction methodology Objective Construction of an SML program computing the function: given its specification S Methodology 1. Case analysis Recognize base case(s), and recursive case(s). 2. Partial correctness f(x) : D R Check that the base case returns correct result. Show that the recursive case gives correct result, assuming that all recursive calls give correct result. 3. Termination Choose a variant. A variant is typically an integer-valued expression on the input parameters together with a lower bound b so that for any recursive call, the variant is b, and for any recursive call, the variant of the recursive call is strictly less than the current call. Sven-Olof Nyström/IT Dept/Uppsala University FP 3.13
14 3.4. Variants in general 3.4. Variants in general Generally, a variant may be any expression whose set of possible values is some set A. For each recursive call, the variant should decrease strictly. There should be no infinite descending chain x 0 > x 1 > x 2 >... in A. Sven-Olof Nyström/IT Dept/Uppsala University FP 3.14
15 3.5. Tips and hints 3.5. Tips and hints Superfluous or overlapping cases Try to keep your code short and compact. Avoid redundant cases! fun fact n = if n = 0 then 1 else if n = 1 then 1 else n fact (n 1) Variants Variants are usually simple; an integer given by a parameter or the size of some input data. But watch out for the difficult cases! Sven-Olof Nyström/IT Dept/Uppsala University FP 3.15
16 3.6. Forms of recursion 3.6. Forms of recursion Up to now: One recursive call Some variant is decremented by one That is: simple recursion (construction process by simple induction) Forms of recursion Simple recursion Complete recursion Multiple recursion Mutual recursion Nested recursion Recursion on a generalised problem Sven-Olof Nyström/IT Dept/Uppsala University FP 3.16
17 3.6. Forms of recursion Complete recursion Example 1: integer division (quotient and remainder) Specification function intdiv a b TYPE: int int (int int) PRE: a 0 and b > 0 POST: (q,r) such that a = q b + r and 0 r < b Construction Variant: a Error case: a < 0 or b 0 : produce an error message Base case: a < b : since a = 0 b + a, return (0,a) This covers more than the minimal value of a (namely 0)! General case: a b : since a = q b + r iff (a b) = (q 1) b + r, the call intdiv (a b) b will give q 1 and r Sven-Olof Nyström/IT Dept/Uppsala University FP 3.17
18 3.6. Forms of recursion Program (intdiv.sml) fun intdivaux a b = if a < b then (0,a) else let val (q1,r1) = intdivaux (a b) b in (q1+1,r1) end fun intdiv a b = if a < 0 orelse b <= 0 then error "intdiv: invalid argument" else intdivaux a b Necessity of the induction hypothesis not only for a 1, but actually for all values less than a: complete induction! Sven-Olof Nyström/IT Dept/Uppsala University FP 3.18
19 3.6. Forms of recursion Example 2: exponentiation (revisited from Section 3.1) Specification function fastexpo x n TYPE: real int real PRE: n 0 POST: x n Construction Variant: n Error case: n < 0: produce an error message Base case: n = 0 : return 1 General case: n > 0 : if n is even, then return x n div 2 x n div 2 otherwise, return x x n div 2 x n div 2 Sven-Olof Nyström/IT Dept/Uppsala University FP 3.19
20 3.6. Forms of recursion Program (expo.sml) fun fastexpo x n = let fun fastexpoaux x 0 = 1.0 fastexpoaux x n = let val r = fastexpoaux x (n div 2) in if even n then r r else x r r end in end if n < 0 then error "fastexpo: negative argument" else fastexpoaux x n Complete recursion, but the size of the input is divided by 2 each time! Complexity Let C(n) be the number of multiplications made (in the worst case) by fastexpo: C(0) = 0 C(n) = C(n div 2) + 2 for n > 0 One can show that C(n) = O(log n) Sven-Olof Nyström/IT Dept/Uppsala University FP 3.20
21 3.6. Forms of recursion Multiple recursion Example: the Fibonacci numbers Definition fib (0) = 1 fib (1) = 1 fib (n) = fib (n 1) + fib (n 2) for n > 1 Specification function fib n TYPE: int int PRE: n 0 POST: fib (n) Program (fib.sml) Variant: n fun fib 0 = 1 fib 1 = 1 fib n = fib (n 1) + fib (n 2) Double recursion Inefficient: multiple recomputations of the same values! Sven-Olof Nyström/IT Dept/Uppsala University FP 3.21
22 3.6. Forms of recursion Mutual recursion Example: recognising even integers and odd integers Specification function even n TYPE: int bool PRE: n 0 POST: true if n is even false otherwise function odd n TYPE: int bool PRE: n 0 POST: true if n is odd false otherwise Program (even.sml) Variant: n fun even 0 = true even n = odd (n 1) and odd 0 = false odd n = even (n 1) Simultaneous declaration of the functions Global correctness reasoning Sven-Olof Nyström/IT Dept/Uppsala University FP 3.22
23 3.6. Forms of recursion Nested recursion and lexicographic order Example 1: the Ackermann function Definition For m, n 0: acker (0,m) = m+1 acker (n,0) = acker (n 1, 1) for n > 0 acker (n,m) = acker (n 1, acker (n, m 1)) for n, m > 0 Program (acker.sml) Variant: the pair (n,m) fun acker 0 m = m+1 acker n 0 = acker (n 1) 1 acker n m = acker (n 1) (acker n (m 1)) where (n, m ) < lex (n, m) iff n < n or (n = n and m < m) This is called a lexicographic order The function acker always terminates It can be shown that Ackermann s function can not be expressed as a primitive-recursive function. Sven-Olof Nyström/IT Dept/Uppsala University FP 3.23
24 3.6. Forms of recursion Example 2: Graham s number, the largest number Definition Operator n (invented by Donald Knuth): a 1 b = a b a n b = a n 1 (b n 1 b) for n > 1 Program (graham.sml) Variant: n fun opknuth 1 a b = Math.pow (a,b) opknuth n a b = opknuth (n 1) a (opknuth (n 1) b b) - opknuth ; val it = E12 : real - opknuth ;! Uncaught exception: Overflow Graham s number is opknuth It is in the Guiness Book of Records! Sven-Olof Nyström/IT Dept/Uppsala University FP 3.24
25 3.6. Forms of recursion Recursion on a generalised problem Example: recognising prime numbers Specification function prime n TYPE: int bool PRE: n > 0 POST: true if n is a prime number false otherwise Construction It is impossible to determine whether n is prime via the reply to the question is n 1 prime? It seems impossible to directly construct a recursive program We thus need to find another function: that is more general than prime, in the sense that prime is a particular case of this function for which a recursive program can be constructed Sven-Olof Nyström/IT Dept/Uppsala University FP 3.25
26 3.6. Forms of recursion Specification of the generalised function function divisors n low up TYPE: int int int bool PRE: n, low, up 1 POST: true if n has no divisors in {low,..., up} false otherwise Construction of a program for the generalised function Variant: up low + 1, which is the size of {low,..., up} Base case: low > up : return true because the set {low,..., up} is empty General case: low up : if n is divisible by low, then return false otherwise, return whether n has a divisor in {low+1,..., up} Construction of a program for the original function The function prime is a particular case of the function divisors, namely when low is 2 and up is n 1 One can also take up as n, and this is more efficient Sven-Olof Nyström/IT Dept/Uppsala University FP 3.26
27 3.6. Forms of recursion Program (prime.sml) fun divisors n low up = low > up orelse (n mod low) <> 0 andalso divisors n (low+1) up fun prime n = if n <= 0 then error "prime: non positive argument" else if n = 1 then false else divisors n 2 (floor (Math.sqrt (real n))) The function divisors may be useful for other problems The discovery of divisors requires imagination and creativity There are some standard methods of generalising problems: let the recursive function take more parameters, so that the problem we want to solve is a special case let the recursive function return more information than is required in the problem statement tupling generalisation: replace a parameter by a list of parameters of the same type Sometimes the only way to solve the problem at hand is to consider a more general problem. Often, a generalized problem may be more efficient regarding time and/or space consumption. Exercises: 1. Which standard method of generalization did we apply in the implementation of the primes function? 2. (Harder) Implement a function that computes fib(n) in time proportional to n. Hint: You will need to define a function that solves a more general problem. Sven-Olof Nyström/IT Dept/Uppsala University FP 3.27
Recursion. Tjark Weber. Functional Programming 1. Based on notes by Sven-Olof Nyström. Tjark Weber (UU) Recursion 1 / 37
Tjark Weber Functional Programming 1 Based on notes by Sven-Olof Nyström Tjark Weber (UU) Recursion 1 / 37 Background FP I / Advanced FP FP I / Advanced FP This course (Functional Programming I) (5 hp,
More informationRecursion. Lars-Henrik Eriksson. Functional Programming 1. Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström
Lars-Henrik Eriksson Functional Programming 1 Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström Tjark Weber (UU) Recursion 1 / 41 Comparison: Imperative/Functional Programming Comparison:
More informationChapter 3 Linear Structures: Lists
Plan Chapter 3 Linear Structures: Lists 1. Lists... 3.2 2. Basic operations... 3.4 3. Constructors and pattern matching... 3.5 4. Polymorphism... 3.8 5. Simple operations on lists... 3.11 6. Application:
More informationChapter 3 Linear Structures: Lists
Plan Chapter 3 Linear Structures: Lists 1. Two constructors for lists... 3.2 2. Lists... 3.3 3. Basic operations... 3.5 4. Constructors and pattern matching... 3.6 5. Simple operations on lists... 3.9
More informationChapter 2 SML, a Functional Programming Language
Plan Chapter 2 SML, a Functional Programming Language 1. Expressions... 2.2 2. Value declarations... 2.13 3. Function declarations... 2.16 4. Type inference... 2.18 5. Anonymous functions... 2.20 6. Specifications...
More information2.1. Expressions. Chapter 2 SML, a Functional Programming Language. Integers. Interacting with ML
Plan Chapter 2 SML, a Functional Programming Language 1. Expressions... 2.2 2. Value declarations... 2.13 3. Function declarations... 2.16 4. Type inference... 2.18 5. Anonymous functions... 2.20 6. Specifications...
More information2.1. Expressions. Chapter 2 ML, a Functional Programming Language. Integers. Interacting with ML
Plan Chapter 2 ML, a Functional Programming Language 1. Expressions... 2.2 2. Value declarations... 2.13 3. Function declarations... 2.16 4. Type inference... 2.18 5. Anonymous functions... 2.20 6. Specifications...
More informationInference rule for Induction
Inference rule for Induction Let P( ) be a predicate with domain the positive integers BASE CASE INDUCTIVE STEP INDUCTIVE Step: Usually a direct proof Assume P(x) for arbitrary x (Inductive Hypothesis),
More informationMAT 243 Test 2 SOLUTIONS, FORM A
MAT 243 Test 2 SOLUTIONS, FORM A 1. [15 points] Calculate the following quantities: a. 17 mod 4 Solution: 17 17 4 = 17 4 4 = 1. 4 b. 17 div 4 17 Solution: = 4. 4 c. (( 1) mod 12) mod (27 div 5) Solution:
More information15 150: Principles of Functional Programming. Exceptions
15 150: Principles of Functional Programming Exceptions Michael Erdmann Spring 2018 1 Topics Exceptions Referential transparency, revisited Examples to be discussed: Dealing with arithmetic errors Making
More informationFunctional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph
Topics Functional Programming Christian Sternagel Harald Zankl Evgeny Zuenko Department of Computer Science University of Innsbruck WS 2017/2018 abstract data types, algebraic data types, binary search
More informationProblem Set CVO 103, Spring 2018
Problem Set CVO 103, Spring 2018 Hakjoo Oh Due: 06/12 (in class) Problem 1 The Fibonacci numbers can be defined as follows: 0 if n = 0 fib(n) = 1 if n = 1 fib(n 1) + fib(n 2) otherwise Write in OCaml the
More information1.3. Conditional expressions To express case distinctions like
Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a
More informationASSIGNMENT 4 SOLUTIONS
MATH 71 ASSIGNMENT SOLUTIONS 1. If F : X X is a function, define f (x) to be (f f)(x), and inductively define f k (x) (f f k 1 )(x) for each integer k. (So f (x) (f f )(x) f(f(f(x))) for instance.) We
More information15 212: Principles of Programming. Some Notes on Induction
5 22: Principles of Programming Some Notes on Induction Michael Erdmann Spring 20 These notes provide a brief introduction to induction for proving properties of ML programs. We assume that the reader
More informationFall Recursion and induction. Stephen Brookes. Lecture 4
15-150 Fall 2018 Stephen Brookes Lecture 4 Recursion and induction Last time Specification format for a function F type assumption guarantee (REQUIRES) (ENSURES) For all (properly typed) x satisfying the
More informationECE G205 Fundamentals of Computer Engineering Fall Exercises in Preparation to the Midterm
ECE G205 Fundamentals of Computer Engineering Fall 2003 Exercises in Preparation to the Midterm The following problems can be solved by either providing the pseudo-codes of the required algorithms or the
More informationRecursion vs Induction
Recursion vs Induction CS3330: Algorithms The University of Iowa 1 1 Recursion Recursion means defining something, such as a function, in terms of itself For example, let f(x) = x! We can define f(x) as
More informationLecture Notes on Induction and Recursion
Lecture Notes on Induction and Recursion 15-317: Constructive Logic Frank Pfenning Lecture 7 September 19, 2017 1 Introduction At this point in the course we have developed a good formal understanding
More informationMathematical Induction
Mathematical Induction Victor Adamchik Fall of 2005 Lecture 3 (out of three) Plan 1. Recursive Definitions 2. Recursively Defined Sets 3. Program Correctness Recursive Definitions Sometimes it is easier
More informationCSE-321 Programming Languages 2010 Midterm
Name: Hemos ID: CSE-321 Programming Languages 2010 Midterm Score Prob 1 Prob 2 Prob 3 Prob 4 Total Max 15 30 35 20 100 1 1 SML Programming [15 pts] Question 1. [5 pts] Give a tail recursive implementation
More informationRecursion vs Induction. CS3330: Algorithms The University of Iowa
Recursion vs Induction CS3330: Algorithms The University of Iowa 1 Recursion Recursion means defining something, such as a function, in terms of itself For example, let f(x) = x! We can define f(x) as
More informationA Brief Introduction to Standard ML
A Brief Introduction to Standard ML Specification and Verification with Higher-Order Logic Arnd Poetzsch-Heffter (Slides by Jens Brandt) Software Technology Group Fachbereich Informatik Technische Universität
More informationLecture 2: The Basis of SML
Lecture 2: The Basis of SML Jean-Noël Monette Functional Programming 1 September 9, 2013 Based on notes by Pierre Flener, Sven-Olof Nyström Jean-Noël Monette (UU) Lecture 2: The Basis of SML 1 / 73 Today
More informationDiscrete Mathematics Lecture 4. Harper Langston New York University
Discrete Mathematics Lecture 4 Harper Langston New York University Sequences Sequence is a set of (usually infinite number of) ordered elements: a 1, a 2,, a n, Each individual element a k is called a
More informationFall Lecture 3 September 4. Stephen Brookes
15-150 Fall 2018 Lecture 3 September 4 Stephen Brookes Today A brief remark about equality types Using patterns Specifying what a function does equality in ML e1 = e2 Only for expressions whose type is
More informationCS 310 Advanced Data Structures and Algorithms
CS 310 Advanced Data Structures and Algorithms Recursion June 27, 2017 Tong Wang UMass Boston CS 310 June 27, 2017 1 / 20 Recursion Recursion means defining something, such as a function, in terms of itself
More informationLecture 3: Recursion; Structural Induction
15-150 Lecture 3: Recursion; Structural Induction Lecture by Dan Licata January 24, 2012 Today, we are going to talk about one of the most important ideas in functional programming, structural recursion
More informationProcessadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)
Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine
More informationInductive Data Types
Inductive Data Types Lars-Henrik Eriksson Functional Programming 1 Original slides by Tjark Weber Lars-Henrik Eriksson (UU) Inductive Data Types 1 / 42 Inductive Data Types Today Today New names for old
More informationAgenda. The worst algorithm in the history of humanity. Asymptotic notations: Big-O, Big-Omega, Theta. An iterative solution
Agenda The worst algorithm in the history of humanity 1 Asymptotic notations: Big-O, Big-Omega, Theta An iterative solution A better iterative solution The repeated squaring trick Fibonacci sequence 2
More informationReduction & Recursion Overview
Reduction & Recursion Overview Reduction definition Reduction techniques Recursion definition Recursive thinking (Many) recursion examples Indirect recursion Runtime stack Factorial isnumericstring add
More informationSolutions to the Second Midterm Exam
CS/Math 240: Intro to Discrete Math 3/27/2011 Instructor: Dieter van Melkebeek Solutions to the Second Midterm Exam Problem 1 This question deals with the following implementation of binary search. Function
More information15 150: Principles of Functional Programming Sorting Integer Lists
15 150: Principles of Functional Programming Sorting Integer Lists Michael Erdmann Spring 2018 1 Background Let s define what we mean for a list of integers to be sorted, by reference to datatypes and
More informationGeneral Computer Science (CH ) Fall 2016 SML Tutorial: Practice Problems
General Computer Science (CH08-320101) Fall 2016 SML Tutorial: Practice Problems November 30, 2016 Abstract This document accompanies the traditional SML tutorial in GenCS. It contains a sequence of simple
More informationFunctions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur
Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself
More informationThis session. Recursion. Planning the development. Software development. COM1022 Functional Programming and Reasoning
This session Recursion COM1022 Functional Programming and Reasoning Dr. Hans Georg Schaathun and Prof. Steve Schneider University of Surrey After this session, you should understand the principle of recursion
More information1KOd17RMoURxjn2 CSE 20 DISCRETE MATH Fall
CSE 20 https://goo.gl/forms/1o 1KOd17RMoURxjn2 DISCRETE MATH Fall 2017 http://cseweb.ucsd.edu/classes/fa17/cse20-ab/ Today's learning goals Explain the steps in a proof by mathematical and/or structural
More informationA First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1
A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner
More informationScan Scheduling Specification and Analysis
Scan Scheduling Specification and Analysis Bruno Dutertre System Design Laboratory SRI International Menlo Park, CA 94025 May 24, 2000 This work was partially funded by DARPA/AFRL under BAE System subcontract
More informationNames and Functions. Chapter 2
Chapter 2 Names and Functions So far we have built only tiny toy programs. To build bigger ones, we need to be able to name things so as to refer to them later. We also need to write expressions whose
More information11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1
RECURSION Chapter 5 Recursive Thinking Section 5.1 1 Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain kinds of problems that are difficult
More informationCSE 215: Foundations of Computer Science Recitation Exercises Set #4 Stony Brook University. Name: ID#: Section #: Score: / 4
CSE 215: Foundations of Computer Science Recitation Exercises Set #4 Stony Brook University Name: ID#: Section #: Score: / 4 Unit 7: Direct Proof Introduction 1. The statement below is true. Rewrite the
More informationCOE428 Lecture Notes Week 1 (Week of January 9, 2017)
COE428 Lecture Notes: Week 1 1 of 10 COE428 Lecture Notes Week 1 (Week of January 9, 2017) Table of Contents COE428 Lecture Notes Week 1 (Week of January 9, 2017)...1 Announcements...1 Topics...1 Informal
More informationELEMENTARY NUMBER THEORY AND METHODS OF PROOF
CHAPTER 4 ELEMENTARY NUMBER THEORY AND METHODS OF PROOF Copyright Cengage Learning. All rights reserved. SECTION 4.3 Direct Proof and Counterexample III: Divisibility Copyright Cengage Learning. All rights
More informationCS 173, Running Time Analysis, Counting, and Dynamic Programming. Tandy Warnow
CS 173, Running Time Analysis, Counting, and Dynamic Programming Tandy Warnow CS 173 September 25, 2018 Tandy Warnow Today Topics: Results from survey Midterm Very basic counting Analyzing running times
More informationFall 2018 Lecture N
15-150 Fall 2018 Lecture N Tuesday, 20 November I m too lazy to figure out the correct number Stephen Brookes midterm2 Mean: 79.5 Std Dev: 18.4 Median: 84 today or, we could procrastinate lazy functional
More informationSML A F unctional Functional Language Language Lecture 19
SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list
More informationRecursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself?
Recursion Chapter 8 CS 3358 Summer I 2012 Jill Seaman What is recursion? Generally, when something contains a reference to itself Math: defining a function in terms of itself Computer science: when a function
More informationReading 8 : Recursion
CS/Math 40: Introduction to Discrete Mathematics Fall 015 Instructors: Beck Hasti, Gautam Prakriya Reading 8 : Recursion 8.1 Recursion Recursion in computer science and mathematics refers to the idea of
More informationSometimes it s good to be lazy
Chapter 8 Sometimes it s good to be lazy Typically, languages such as OCaml (SML, Lisp or Scheme) evaluate expressions by a call-by-value discipline. All variables in OCaml are bound by value, which means
More informationAnatomy of a static method, S&W, 2.1, figure page 188. Class.name or just name Scope, S&W, 2.1, figure page 189. Overloading
Static Methods Anatomy of a static method, S&W, 2.1, figure page 188. Class.name or just name Scope, S&W, 2.1, figure page 189. Overloading public static int abs (final int x) { return x
More informationHigher-Order Functions
Higher-Order Functions Tjark Weber Functional Programming 1 Based on notes by Pierre Flener, Jean-Noël Monette, Sven-Olof Nyström Tjark Weber (UU) Higher-Order Functions 1 / 1 Tail Recursion http://xkcd.com/1270/
More informationAbout coding style Spring February 9, 2004
About codg style 15-212 Sprg 2004 February 9, 2004 Contents 1 Correctness 2 2 Specification 2 3 Style 2 3.1 if-then- Expressions... 3 3.1.1 Boolean if-then- Expressions... 3 3.1.2 if-then- stead of Pattern
More informationCSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions
CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions User Defined Functions In previous labs, you've encountered useful functions, such as sqrt() and pow(), that were created by other
More informationFunctional Programming
Functional Programming Function evaluation is the basic concept for a programming paradigm that has been implemented in functional programming languages. The language ML ( Meta Language ) was originally
More informationChapter 1 Programming: A General Overview
Chapter 1 Programming: A General Overview 2 Introduction This class is an introduction to the design, implementation, and analysis of algorithms. Examples: sorting large amounts of data organizing information
More informationA quick introduction to SML
A quick introduction to SML CMSC 15300 April 9, 2004 1 Introduction Standard ML (SML) is a functional language (or higherorder language) and we will use it in this course to illustrate some of the important
More informationAlgorithm Design: GCD
Algorithm Design: GCD Problem solution through refinement GCD Example of use of loops Arguing the complexity of an algorithm Greek mathematics achievement: Euclid s Algorithm 1 How to find the GCD of 2
More informationAPCS-AB: Java. Recursion in Java December 12, week14 1
APCS-AB: Java Recursion in Java December 12, 2005 week14 1 Check point Double Linked List - extra project grade Must turn in today MBCS - Chapter 1 Installation Exercises Analysis Questions week14 2 Scheme
More informationELEMENTARY NUMBER THEORY AND METHODS OF PROOF
CHAPTER 4 ELEMENTARY NUMBER THEORY AND METHODS OF PROOF Copyright Cengage Learning. All rights reserved. SECTION 4.3 Direct Proof and Counterexample III: Divisibility Copyright Cengage Learning. All rights
More informationChapter 6 Abstract Datatypes
Plan Chapter 6 Abstract Datatypes (Version of 17 November 2005) 1. Application: correctly parenthesised texts...... 6.2 2. An abstract datatype for stacks................ 6.6 3. Realisation of the stack
More informationOutline. Introduction. 2 Proof of Correctness. 3 Final Notes. Precondition P 1 : Inputs include
Outline Computer Science 331 Correctness of Algorithms Mike Jacobson Department of Computer Science University of Calgary Lectures #2-4 1 What is a? Applications 2 Recursive Algorithms 3 Final Notes Additional
More informationP1 Engineering Computation
1EC 2001 1 / 1 P1 Engineering Computation David Murray david.murray@eng.ox.ac.uk www.robots.ox.ac.uk/ dwm/courses/1ec Hilary 2001 1EC 2001 2 / 1 Algorithms: Design, Constructs and Correctness 1EC 2001
More informationCS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called
CS109A ML Notes for the Week of 1/16/96 Using ML ML can be used as an interactive language. We shall use a version running under UNIX, called SML/NJ or \Standard ML of New Jersey." You can get SML/NJ by
More informationA catalogue of proofs that various sets, functions and relations are primitive recursive 26 February 2012 at 20:57
A catalogue of proofs that various sets, functions and relations are primitive recursive 26 February 2012 at 20:57 Public In this note (which is mainly intended as a 'memo' for myself) I am interested
More informationRecursion. Chapter 5
Recursion Chapter 5 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how to write recursive algorithms and methods for searching arrays To learn
More informationAlgorithm Analysis. (Algorithm Analysis ) Data Structures and Programming Spring / 48
Algorithm Analysis (Algorithm Analysis ) Data Structures and Programming Spring 2018 1 / 48 What is an Algorithm? An algorithm is a clearly specified set of instructions to be followed to solve a problem
More informationProgramming & Data Structure Laboratory. Day 2, July 24, 2014
Programming & Data Structure Laboratory Day 2, July 24, 2014 Loops Pre and post test loops for while do-while switch-case Pre-test loop and post-test loop Condition checking True Loop Body False Loop Body
More informationRecursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem
Recursion Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem What is Recursion? A problem is decomposed into smaller sub-problems, one or more of which are simpler versions of
More informationRecursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? contains a reference to itself.
Recursion Chapter 8 CS 3358 Summer II 2013 Jill Seaman What is recursion?! Generally, when something contains a reference to itself! Math: defining a function in terms of itself! Computer science: when
More informationTail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1))))))
Tail Recursion 1 Tail Recursion In place of loops, in a functional language one employs recursive definitions of functions. It is often easy to write such definitions, given a problem statement. Unfortunately,
More informationRecursion Chapter 4 Self-Reference. Recursive Definitions Inductive Proofs Implementing Recursion
Recursion Chapter 4 Self-Reference Recursive Definitions Inductive Proofs Implementing Recursion Imperative Algorithms Based on a basic abstract machine model - linear execution model - storage - control
More informationFunctional Programming Languages (FPL)
Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional
More informationRecursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011
Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion A method calling itself Overview A new way of thinking about a problem Divide and conquer A powerful programming
More informationTwo Approaches to Algorithms An Example (1) Iteration (2) Recursion
2. Recursion Algorithm Two Approaches to Algorithms (1) Iteration It exploits while-loop, for-loop, repeat-until etc. Classical, conventional, and general approach (2) Recursion Self-function call It exploits
More informationRecursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...
Recursion Recursion Overview A method calling itself A new way of thinking about a problem Divide and conquer A powerful programming paradigm Related to mathematical induction Example applications Factorial
More informationLoops / Repetition Statements
Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for
More informationLecture 6: Arithmetic and Threshold Circuits
IAS/PCMI Summer Session 2000 Clay Mathematics Undergraduate Program Advanced Course on Computational Complexity Lecture 6: Arithmetic and Threshold Circuits David Mix Barrington and Alexis Maciel July
More informationHW 1 CMSC 452. Morally DUE Feb 7 NOTE- THIS HW IS THREE PAGES LONG!!! SOLUTIONS THROUGOUT THIS HW YOU CAN ASSUME:
HW 1 CMSC 452. Morally DUE Feb 7 NOTE- THIS HW IS THREE PAGES LONG!!! SOLUTIONS THROUGOUT THIS HW YOU CAN ASSUME: The union of a finite number of countable sets is countable. The union of a countable number
More informationRichard Feynman, Lectures on Computation
Chapter 8 Sorting and Sequencing If you keep proving stuff that others have done, getting confidence, increasing the complexities of your solutions for the fun of it then one day you ll turn around and
More informationCS 3512, Spring Instructor: Doug Dunham. Textbook: James L. Hein, Discrete Structures, Logic, and Computability, 3rd Ed. Jones and Barlett, 2010
CS 3512, Spring 2011 Instructor: Doug Dunham Textbook: James L. Hein, Discrete Structures, Logic, and Computability, 3rd Ed. Jones and Barlett, 2010 Prerequisites: Calc I, CS2511 Rough course outline:
More informationProgram Calculus Calculational Programming
Program Calculus Calculational Programming National Institute of Informatics June 21 / June 28 / July 5, 2010 Program Calculus Calculational Programming What we will learn? Discussing the mathematical
More informationCSC236H Lecture 5. October 17, 2018
CSC236H Lecture 5 October 17, 2018 Runtime of recursive programs def fact1(n): if n == 1: return 1 else: return n * fact1(n-1) (a) Base case: T (1) = c (constant amount of work) (b) Recursive call: T
More informationHOMEWORK FILE SOLUTIONS
Data Structures Course (CSCI-UA 102) Professor Yap Spring 2012 HOMEWORK FILE February 13, 2012 SOLUTIONS 1 Homework 2: Due on Thu Feb 16 Q1. Consider the following function called crossproduct: int crossproduct(int[]
More informationNumber System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value
1 Number System Introduction In this chapter, we will study about the number system and number line. We will also learn about the four fundamental operations on whole numbers and their properties. Natural
More informationCS 3410 Ch 7 Recursion
CS 3410 Ch 7 Recursion Sections Pages 7.1-7.4, 7.7 93-319, 333-336 7.1 Introduction 1. A recursive method is a method that either directly or indirectly makes a call to itself. [Weiss]. It does this by
More informationSolutions to Homework 10
CS/Math 240: Intro to Discrete Math 5/3/20 Instructor: Dieter van Melkebeek Solutions to Homework 0 Problem There were five different languages in Problem 4 of Homework 9. The Language D 0 Recall that
More informationBegin at the beginning
Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of
More informationLecture 10: Recursion vs Iteration
cs2010: algorithms and data structures Lecture 10: Recursion vs Iteration Vasileios Koutavas School of Computer Science and Statistics Trinity College Dublin how methods execute Call stack: is a stack
More informationCITS3001. Algorithms, Agents and Artificial Intelligence. Semester 2, 2016
CITS3001 Algorithms, Agents and Artificial Intelligence Semester 2, 2016 Tim French School of Computer Science & Software Eng. The University of Western Australia 2. Review of algorithmic concepts CLRS,
More informationTypes of Recursive Methods
Types of Recursive Methods Types of Recursive Methods Direct and Indirect Recursive Methods Nested and Non-Nested Recursive Methods Tail and Non-Tail Recursive Methods Linear and Tree Recursive Methods
More informationAssertions & Verification & Example Loop Invariants Example Exam Questions
2014 November 27 1. Assertions & Verification & Example Loop Invariants Example Exam Questions 2. A B C Give a general template for refining an operation into a sequence and state what questions a designer
More informationIntro to Computational Programming in C Engineering For Kids!
CONTROL STRUCTURES CONDITIONAL EXPRESSIONS Take the construction like this: Simple example: if (conditional expression) statement(s) we do if the condition is true statement(s) we do if the condition is
More informationTECH. Recurrence Equations vs. Recursive Procedures. Recursion and Induction. e.g. Fibonacci Function. The working of recursive procedure
Recursion and Induction For advanced algorithm development, recursion is an essential design technique Recursive Procedures What is a Proof? Induction Proofs Proving Correctness of Procedures Recurrence
More informationFinal Examination: Topics and Sample Problems
Computer Science 52 Final Examination: Topics and Sample Problems Spring Semester, 2015 In examinations the foolish ask questions that the wise cannot answer. Oscar Wilde, 1894 Time and Place Wednesday,
More informationCSE 341 Section 5. Winter 2018
CSE 341 Section 5 Winter 2018 Midterm Review! Variable Bindings, Shadowing, Let Expressions Boolean, Comparison and Arithmetic Operations Equality Types Types, Datatypes, Type synonyms Tuples, Records
More informationNote that pcall can be implemented using futures. That is, instead of. we can use
Note that pcall can be implemented using futures. That is, instead of (pcall F X Y Z) we can use ((future F) (future X) (future Y) (future Z)) In fact the latter version is actually more parallel execution
More informationUnit #3: Recursion, Induction, and Loop Invariants
Unit #3: Recursion, Induction, and Loop Invariants CPSC 221: Basic Algorithms and Data Structures Jan Manuch 2017S1: May June 2017 Unit Outline Thinking Recursively Recursion Examples Analyzing Recursion:
More informationIf we have a call. Now consider fastmap, a version of map that uses futures: Now look at the call. That is, instead of
If we have a call (map slow-function long-list where slow-function executes slowly and long-list is a large data structure, we can expect to wait quite a while for computation of the result list to complete.
More information