Foundations of Computation

Size: px
Start display at page:

Download "Foundations of Computation"

Transcription

1 The Australian National University Semester 2, 2018 Research School of Computer Science Tutorial 5 Dirk Pattinson Foundations of Computation The tutorial contains a number of exercises designed for the students to practice the course content. During the lab, the tutor will work through some of these exercises while the students will be responsible for completing the remaining exercises in their own time. There is no expectation that all the exercises will be covered in lab time. Exercise 1 Consider the following definition of binary trees Reversing a binary tree data Tree a = Nul Node (Tree a) a (Tree a) along with the function that reverses binary trees: revt :: Tree a -> Tree a revt Nul = Nul -- T1 revt (Node t1 x t2) = Node (revt t2) x (revt t1) -- T2 1. Use tree induction to show that the equation revt (revt t) = t is true for all trees t of type Tree a. We prove t.p (t) by induction (on t) where P (t) = revt (revt t) = t. Base Case revt (revt Nul) = Nul revt (revt Nul) = revt Nul -- by T1 = Nul -- by T1 Step Case Assume revt (revt a1) = a1 -- (IH1) revt (revt a2) = a2 -- (IH2) Prove revt (revt (Node a1 x a2)) = Node a1 x a2 revt (revt (Node a1 x a2)) = revt (Node (revt a2) x (revt a1)) -- by T2 = Node (revt (revt a1)) x (revt (revt a2)) -- by T2 = Node a1 x a2 -- by IH1, IH2 Having showed P (a1) P (a2) P (Node a1 x a2), we can generalise to y. t1. t2.p (t1) P (t2) P (Node t1 y t2). Having showed P (Nul) and y. t1. t2.p (t1) P (t2) P (Node t1 y t2), we have t.p (t). 2. Show that reversing a tree does not increase or decrease the number of its nodes, that is, establish that holds for all trees t of type Tree a. count(revt t) = count (t) We prove t.p (t) by induction on t where P (t) = count(revt t) = count (t). Base Case count(revt Nul) = count Nul = count Nul -- by T1 Step Case Assume

2 count(revt a1) = count a1 count(revt a2) = count a2 -- (IH1) -- (IH2) Prove count (revt (Node a1 x a2)) = count (Node a1 x a2) count (revt (Node a1 x a2)) = count (Node (revt a2) x (revt a1)) -- by T2 = 1 + count (revt a2) + count (revt a1) -- by C2 = 1 + (count a2) + (count a1) -- by IH2, IH1 = 1 + (count a1) + (count a2) -- by commutativity of + = count (Node a1 x a2) -- by C2 Having showed P (a1) P (a2) P (Node a1 x a2), we can generalise to y. t1. t2.p (t1) P (t2) P (Node t1 y t2). Having showed P (Nul) and y. t1. t2.p (t1) P (t2) P (Node t1 x t2), we have t.p (t). Exercise 2 Flattening a Tree We can turn a tree into a list containing the same entries with the tail recursive function flat, where flat t acc returns the result of flattening the tree t, appended to the front of the list acc. For example, flat (Node (Node Nul 3 Nul) 5 (Node Nul 6 Nul)) [1,2] = [3,5,6,1,2] flat :: Tree a -> [a] -> [a] flat Nul acc = acc -- (F1) flat (Node t1 a t2) acc = flat t1 (a : flat t2 acc) -- (F2) We can get the sum of entries in a list by the function suml suml :: [Int] -> Int suml [] = 0 -- (S1) suml (x:xs) = x + suml xs -- (S2) We can get the sum of entries in a tree by the function sumt sumt :: Tree Int -> Int sumt Nul = 0 -- (T1) sumt (Node t1 n t2) = n + sumt t1 + sumt t2 -- (T2) Prove (using tree induction) that for all t and acc, suml (flat t acc) = sumt t + suml acc Base case: t = Nul. Show that suml (flat Nul acc) = sumt Nul + suml acc Proof: suml (flat Nul acc) = suml acc -- by (F1) = 0 + suml acc -- by arithmetic = sumt Nul + suml acc -- by (T1) The inductive hypotheses: acc suml (flat t1 acc) = sumt t1 + suml acc -- (IH1) suml (flat t2 acc) = sumt t2 + suml acc -- (IH2)

3 Step case: Show (assuming the IHs), that acc, suml (flat (Node t1 y t2) acc = sumt (Node t1 y t2) + suml acc Proof: suml (flat (Node t1 y t2) acc) = suml (flat t1 (y : flat t2 acc)) -- by (F2) = sumt t1 + suml (y : flat t2 acc) -- by (IH1) = sumt t1 + y + suml (flat t2 acc) -- by (S2) = sumt t1 + y + sumt t2 + suml acc -- by (IH2) = sumt (Node t1 y t2) + suml acc -- by (T2) Note: (IH1) is instantiated so that acc becomes (y : flat t2 acc), but the acc of (IH2) is just instantiated to the acc of the proof. Note: the proof involves steps which use associativity or commutativity of +; these steps are not explicitly shown. Exercise 3 Soup Induction In the military, there are very strict rules regarding how to make soup: an empty pot of water is a soup, and given a soup, a new soup can be created by adding (precisely) two carrots and one turnip. We can model these soups using the inductive data type Soup that takes the type of carrots and the type of turnips as parameters: data Soup carrot turnip = Water MkSoup carrot carrot turnip (Soup carrot turnip) 1. Let s call the induction principle for the above type soup induction. Assuming that you want to establish that P (s) holds for all elements of this data type, what do you need to establish in terms of the constructors? We need to show that P (Water) c 1. c 2. t. s.p (s) P (MkSoup c 1 c 2 t s). 2. We are given the following functions that count the number of carrots and turnips in a soup. noturnips :: Soup carrot turnip -> Int noturnips Water = 0 noturnips (MkSoup c1 c2 t s) = 1 + noturnips s nocarrots :: Soup carrot turnip -> Int nocarrots Water = 0 nocarrots (MkSoup c1 c2 t s) = 2 + nocarrots s -- NT1 -- NT2 -- NC1 -- NC2 Establish, using soup induction, that nocarrots s = 2 * noturnips s holds for all s of type Soup carrot turnip. We go through both cases of the induction principle for soups above. Base case. Show that nocarrots Water = 2 * noturnips Water.

4 nocarrots Water = 0 -- NC1 = 2 * 0 -- arith = 2 * noturnips Water -- NT1 Step Case. Assume that nocarrots s = 2 * noturnips s -- IH for an arbitrary soup s and let c1, c2 and t be arbitrary elements of the types carrot and turnip, respectively. We need to show that nocarrots (MkSoup c1 c2 t s) = 2 * noturnips (MkSoup c1 c2 t s) Our reasoning is as follows: nocarrots (MkSoup c1 c2 t s) = 2 + nocarrots s -- NC2 = * noturnips s -- IH = 2 * (1 + noturnips s) -- arith = 2 * noturnips (MkSoup c1 c2 t s) -- NT2 Exercise 4 Tree Reversal, Again Consider the function revt given in the first exercise, along with the function mapt discussed in the lectures: mapt f Nul = Nul -- (M1) mapt f (Node t1 x t2) = Node (mapt f t1) (f x) (mapt f t2) -- (M2) Establish, using tree induction, that mapt f (revt t) = revt (mapt f t) holds for all functions f :: a -> b and all trees t of type Tree a. Fix an arbitrary function f: a -> b. Base Case. We need to show that This is easy: mapt f (revt Nul) = mapt f (Nul) -- T1 = Nul -- M1 = revt (Nul) -- T1 = revt (mapt f Nul) -- M1 mapt f (revt Nul) = revt (mapt f Nul) Step Case. Assume that, for arbitrary trees l and r of type Tree a mapt f (revt l) = revt (mapt f l) mapt f (revt r) = revt (mapt f r) -- IH1 -- IH2 holds. We show that holds, as well. We argue as follows: mapt f (revt (Node l x r)) = revt (mapt f (Node l x r) mapt f (revt (Node l x r)) = mapt f (Node (revt r) x (revt l)) -- T2 = Node (mapt f (revt r)) (f x) (mapt f (revt l)) -- M2 = Node (revt (mapt f r)) (f x) (revt (mapt f r)) -- IH1, IH2 = revt (Node (mapt f l) (f x) (mapt f r)) -- T2 = revt (mapt f (Node l x r)) -- M2

5 Exercise 5 Sorted Lists and Insertion The goal of this exercise is to show inserting an element into a sorted list using the function insert :: Int -> [Int] -> [Int] insert x [] = [x] insert x (y:ys) x < y = x:y:ys otherwise = y:(insert x ys) produces an sorted list as a result. We don t define what sorted means precisely (in logic) but use informal reasoning instead. The goal of the exercise is to demonstrate how we can use induction to reason about a subset of an inductively defined type (such as the set of all sorted lists). 1. Use a predicate sorted(l) that expresses that the list l is sorted, to express the statement Inserting an arbitrary element x into a sorted list l using the insert-function produces a sorted list. 2. Establish this property using list induction. You may assume basic properties of the predicate sorted, such as the fact that x:y:ys is sorted if y:ys is sorted, and x < y. 1. We re-formulate the property to say for all lists l and all integers x, if l is sorted, then insert x l is sorted. This gives the formula l. x.sorted(l) sorted(insert x l). 2. We now establish this property using list induction. Base Case. We show that x.sorted([]) sorted(insert x []). This follows, because insert x [] = [x] is clearly a sorted list. Step Case. Assume that and show that x.sorted(ys) sorted(insert x ys) x.sorted(y : ys) sorted(insert x y : ys). Let x be arbitrary. We need to establish an implication sorted(y : ys) sorted(insert x (y : ys)) and hence assume that y:ys is sorted, and we need to show that insert x (y:ys) is sorted. We distinguish two cases: Case 1. x < y. Then insert x (y:ys) = x:y:ys by definition of insert, and as y:ys is sorted and x < y we obtain that x:y:ys is sorted. Case 2. x >= ys. Then insert x (y:ys) = y:(insert x ys) by definition of sorted. By inductive hypothesis, we have that insert x ys is sorted, therefore y:(insert x ys) is sorted, too, as y is the smallest element of y:ys (as ys is sorted) and also y <= x. Exercise 6 Leaf Nodes and Tree Height Consider the following two functions that determine the height of a tree, and the number of its leaves, respectively: height :: Tree a -> Int height Nul = 1 -- H1 height (Node l x r) = 1 + max (height l) (height r) -- H2 leaves :: Tree a -> Int leaves Nul = 1 leaves (Node l x r) = (leaves l) + (leaves r) -- L1 -- L2

6 Show, using tree induction, that holds for all trees t of type Tree a. 1 + leaves t <= 2ˆ(height t) Clearly state what you need to prove for the base case, the inductive hypothesis, and what you need to show in the step case. Marks. 1 for base case, and 2 for step case: 0.5 for stating IH and proof goal, and 1.5 for the reasoning. Base Case. Show that 1 + leaves Nul <= 2ˆ(height Nul). 1 + leaves Nul = L1 = 2ˆ1 -- arith = 2ˆ(height Nul) -- H1 <= 2ˆ(height Nul) -- arith Step Case. Assume that for arbitrary trees l and r we have that Show that 1 + leaves l <= 2ˆ(height l) -- IHl 1 + leaves r <= 2ˆ(height r) -- IHr 1 + leaves (Node l x r) <= 2ˆ(height (Node l x r)). for an arbitrary element x of type a. This holds, and can be seen e.g. as follows: Exercise leaves (Node l x r) <= (leaves l) + (leaves r) -- L2 <= 2ˆ(height l) + 2ˆ(height r) -- IHl, IHr <= 2 * 2ˆ(max (height l) (height r)) -- arith = 2ˆ (1 + max (height l) (height r)) -- arith = 2ˆ(height (Node l x r)) -- H2 Flattening and Elem Consider the (non tail-recursive) function flatten that flattens a tree into a list: flatten :: Tree a -> [a] flatten Nul = [] flatten (Node l x r) = (flatten l) ++ [x] ++ (flatten r) -- SF1 -- SF2 together with the function elemt given by elemt :: Eq a => a -> Tree a -> Bool elemt y Nul = False -- ET1 elemt y (Node l x r) x == y = True -- ET2 otherwise = (elemt y l) (elemt y r) -- ET3 Show, using tree induction, that for all t of type Tree a and all e of type a. elmt e t = elem e (flatten t) Hint. You may want to use Exercise 5 on Tutorial Sheet 4. You may also want to use the equality proved there. It may be helpful to first establish the value of elem e [x]. Clearly state what you need to prove for the base case, the inductive hypothesis, and what you need to show in the step case. Marks. 1 for the base case, 3 for each of the cases in the step case: 1 for demonstrating the elem x [e] case, 0.5 for stating IH and proof goal, and 1.5 for the reasoning. Base Case. Show that elemt e Nul = elem e (flatten Nul).

7 elemt e Nul = False -- ET1 = elem e [] -- E1 = elem e (flatten Nul) -- SF1 Step Case. We distinguish two cases, and first consider the case where x e. We first show that elem e [x] = False. This follows, as elem e [x] = elem e (x::[]) = elem e [] -- E2 = False and [x] = x:[]. This gives the following reasoning for the case of x e: elemt e (Node l x r) = = (elemt e l) (elemt e r) = -- ET3 = (elem e (flatten l)) elem e (flatten r) = -- IH = (elem e (flatten l)) (False elem e (flatten r)) = -- O2 = (elem e (flatten l) (elem e [x]) elem e (flatten r) -- as before = (elem e (flatten l) (elem e ([x] ++ flatten r) -- Ex 5, Tut 4 = (elem e (flatten l) ++ [x] ++ (flatten r) -- Ex 5, Tut 4 = elem e (flatten (Node l x r) -- SF2 Now, for the case x = e we show that elem e [x] = True: elem e [x] = elem e (x:[]) = True -- E2 This gives the following reasoning for the case where x = e: elemt e (Node l x r) = True -- ET1 = (elem e (flatten l)) True -- O1 = (elem e (flatten l)) True (elem e (flatten r)) -- O1 = (elem e (flatten l)) (elem e [x]) (elem e (flatten r)) -- as before = (elem e (flatten l) (elem e ([x] ++ (elem e (flatten r)) -- Ex 5, Tut 4 = (elem e (flatten l) ++ [x] ++ (flatten r) -- Ex 5, Tut 4 = elem e (flatten (Node l x r)

8 Appendix: Function definitions count :: Tree a -> Int count Nul = 0 -- C1 count (Node t1 x t2) = 1 + count t1 + count t2 -- C2 map :: (a -> b) -> [a] -> [b] map f [] = [] -- M1 map f (x:xs) = f x : map f xs -- M2 (++) :: [a] -> [a] -> [a] [] ++ ys = ys -- A1 (x:xs) ++ ys = x : (xs ++ ys) -- A2 elem :: Eq a => a -> [a] -> Bool elem y [] = False -- E1 elem y (x:xs) x == y = True -- E2 otherwise = elem y xs -- E3 ( ) :: Bool -> Bool -> Bool True _ = True -- O1 False x = x -- O2

Week 5 Tutorial Structural Induction

Week 5 Tutorial Structural Induction Department of Computer Science, Australian National University COMP2600 / COMP6260 Formal Methods in Software Engineering Semester 2, 2016 Week 5 Tutorial Structural Induction You should hand in attempts

More information

Induction for Data Types

Induction for Data Types Induction for Data Types COMP1600 / COMP6260 Dirk Pattinson Australian National University Semester 2, 2017 Catch Up / Drop in Lab When Fridays, 15.00-17.00 Where N335, CSIT Building (bldg 108) Until the

More information

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product

More information

Programming Languages 3. Definition and Proof by Induction

Programming Languages 3. Definition and Proof by Induction Programming Languages 3. Definition and Proof by Induction Shin-Cheng Mu Oct. 22, 2015 Total Functional Programming The next few lectures concerns inductive definitions and proofs of datatypes and programs.

More information

Shell CSCE 314 TAMU. Functions continued

Shell CSCE 314 TAMU. Functions continued 1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in

More information

Lecture 6: Sequential Sorting

Lecture 6: Sequential Sorting 15-150 Lecture 6: Sequential Sorting Lecture by Dan Licata February 2, 2012 Today s lecture is about sorting. Along the way, we ll learn about divide and conquer algorithms, the tree method, and complete

More information

Programming in Haskell Aug-Nov 2015

Programming in Haskell Aug-Nov 2015 Programming in Haskell Aug-Nov 2015 LECTURE 11 SEPTEMBER 10, 2015 S P SURESH CHENNAI MATHEMATICAL INSTITUTE Measuring efficiency Measuring efficiency Computation is reduction Application of definitions

More information

Informatics 1 Functional Programming Lecture 11. Data Representation. Don Sannella University of Edinburgh

Informatics 1 Functional Programming Lecture 11. Data Representation. Don Sannella University of Edinburgh Informatics 1 Functional Programming Lecture 11 Data Representation Don Sannella University of Edinburgh Part I Complexity t = n vs t = n 2 10.4 9.6 8.8 8 7.2 6.4 5.6 4.8 4 3.2 2.4 1.6 0.8 0 0.8 1.6 2.4

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee 1 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as

More information

Shell CSCE 314 TAMU. Higher Order Functions

Shell CSCE 314 TAMU. Higher Order Functions 1 CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions 2 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result.

More information

Informatics 1 Functional Programming Lecture 12. Data Abstraction. Don Sannella University of Edinburgh

Informatics 1 Functional Programming Lecture 12. Data Abstraction. Don Sannella University of Edinburgh Informatics 1 Functional Programming Lecture 12 Data Abstraction Don Sannella University of Edinburgh Part I Sets as lists without abstraction We will look again at our four ways of implementing sets.

More information

Reasoning about programs. Chapter 9 of Thompson

Reasoning about programs. Chapter 9 of Thompson Reasoning about programs Chapter 9 of Thompson Proof versus testing A proof will state some property of a program that holds for all inputs. Testing shows only that a property holds for a particular set

More information

CITS3211 FUNCTIONAL PROGRAMMING. 6. Folding operators

CITS3211 FUNCTIONAL PROGRAMMING. 6. Folding operators CITS3211 FUNCTIONAL PROGRAMMING 6. Folding operators Summary: This lecture discusses an important group of higher order functions known as the folding operators. Almost any recursive function over lists

More information

Introduction to Programming, Aug-Dec 2006

Introduction to Programming, Aug-Dec 2006 Introduction to Programming, Aug-Dec 2006 Lecture 3, Friday 11 Aug 2006 Lists... We can implicitly decompose a list into its head and tail by providing a pattern with two variables to denote the two components

More information

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

Functional 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 information

Recursion and Structural Induction

Recursion and Structural Induction Recursion and Structural Induction Mukulika Ghosh Fall 2018 Based on slides by Dr. Hyunyoung Lee Recursively Defined Functions Recursively Defined Functions Suppose we have a function with the set of non-negative

More information

Inference rule for Induction

Inference 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 information

Functional Programming Mid-term exam Tuesday 3/10/2017

Functional Programming Mid-term exam Tuesday 3/10/2017 Functional Programming Mid-term exam Tuesday 3/10/2017 Name: Student number: Before you begin: Do not forget to write down your name and student number above. If necessary, explain your answers in English.

More information

Haskell Types, Classes, and Functions, Currying, and Polymorphism

Haskell Types, Classes, and Functions, Currying, and Polymorphism 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Types, Classes, and Functions, Currying, and Polymorphism 2 Types A type is a collection of related values. For example, Bool contains the

More information

Introduction to Programming: Lecture 6

Introduction to Programming: Lecture 6 Introduction to Programming: Lecture 6 K Narayan Kumar Chennai Mathematical Institute http://www.cmi.ac.in/~kumar 28 August 2012 Example: initial segments Write a Haskell function initsegs which returns

More information

Recursively Defined Functions

Recursively Defined Functions Section 5.3 Recursively Defined Functions Definition: A recursive or inductive definition of a function consists of two steps. BASIS STEP: Specify the value of the function at zero. RECURSIVE STEP: Give

More information

Proving Properties of Recursive Functions and Data Structures. CS 270 Math Foundations of CS Jeremy Johnson

Proving Properties of Recursive Functions and Data Structures. CS 270 Math Foundations of CS Jeremy Johnson Proving Properties of Recursive Functions and Data Structures CS 270 Math Foundations of CS Jeremy Johnson 1 Objective To implement and verify recursive functions for processing recursive data structures.

More information

Definition For vertices u, v V (G), the distance from u to v, denoted d(u, v), in G is the length of a shortest u, v-path. 1

Definition For vertices u, v V (G), the distance from u to v, denoted d(u, v), in G is the length of a shortest u, v-path. 1 Graph fundamentals Bipartite graph characterization Lemma. If a graph contains an odd closed walk, then it contains an odd cycle. Proof strategy: Consider a shortest closed odd walk W. If W is not a cycle,

More information

Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences

Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences Section 5.3 1 Recursion 2 Recursion Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences Previously sequences were defined using a specific

More information

MoreIntro_annotated.v. MoreIntro_annotated.v. Printed by Zach Tatlock. Oct 04, 16 21:55 Page 1/10

MoreIntro_annotated.v. MoreIntro_annotated.v. Printed by Zach Tatlock. Oct 04, 16 21:55 Page 1/10 Oct 04, 16 21:55 Page 1/10 * Lecture 02 Infer some type arguments automatically. Set Implicit Arguments. Note that the type constructor for functions (arrow " >") associates to the right: A > B > C = A

More information

1KOd17RMoURxjn2 CSE 20 DISCRETE MATH Fall

1KOd17RMoURxjn2 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 information

Exercise 1 ( = 24 points)

Exercise 1 ( = 24 points) 1 Exercise 1 (4 + 5 + 4 + 6 + 5 = 24 points) The following data structure represents polymorphic binary trees that contain values only in special Value nodes that have a single successor: data Tree a =

More information

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm Sample Solutions CSC324H1 Duration: 50 minutes Instructor(s): David Liu.

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm Sample Solutions CSC324H1 Duration: 50 minutes Instructor(s): David Liu. UNIVERSITY OF TORONTO Faculty of Arts and Science Midterm Sample s CSC324H1 Duration: 50 minutes Instructor(s): David Liu. No Aids Allowed Name: Student Number: Please read the following guidelines carefully.

More information

Programming Paradigms Written Exam

Programming Paradigms Written Exam Programming Paradigms Written Exam 17.06.2014 First name Student number Last name Signature Instructions for Students Write your name and student number on the exam sheet and on every solution sheet you

More information

Haskell Overview II (2A) Young Won Lim 8/9/16

Haskell Overview II (2A) Young Won Lim 8/9/16 (2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

Cornell University 12 Oct Solutions. (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below.

Cornell University 12 Oct Solutions. (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below. Cornell University 12 Oct 2006 Solutions 1. Types, Polymorphism [14 pts] (parts a b) (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below. i. fun f x y = (y,

More information

Solutions. (a) Claim: A d-ary tree of height h has at most 1 + d +...

Solutions. (a) Claim: A d-ary tree of height h has at most 1 + d +... Design and Analysis of Algorithms nd August, 016 Problem Sheet 1 Solutions Sushant Agarwal Solutions 1. A d-ary tree is a rooted tree in which each node has at most d children. Show that any d-ary tree

More information

Recursive Definitions Structural Induction Recursive Algorithms

Recursive Definitions Structural Induction Recursive Algorithms Chapter 4 1 4.3-4.4 Recursive Definitions Structural Induction Recursive Algorithms 2 Section 4.1 3 Principle of Mathematical Induction Principle of Mathematical Induction: To prove that P(n) is true for

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

Theorem Proving Principles, Techniques, Applications Recursion

Theorem Proving Principles, Techniques, Applications Recursion NICTA Advanced Course Theorem Proving Principles, Techniques, Applications Recursion 1 CONTENT Intro & motivation, getting started with Isabelle Foundations & Principles Lambda Calculus Higher Order Logic,

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

Exam Informatik D-MATH/D-PHYS :00 11:00

Exam Informatik D-MATH/D-PHYS :00 11:00 Exam Informatik D-MATH/D-PHYS 25. 1. 2013 09:00 11:00 Dr. Bernd Gartner Examinee: Last name:... First name:... Stud. no.:... With my signature I attest, that I was able to sit the exam under regular conditions

More information

Inductive Data Types

Inductive 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 information

Testing. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 2. [Faculty of Science Information and Computing Sciences]

Testing. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 2. [Faculty of Science Information and Computing Sciences] Testing Advanced functional programming - Lecture 2 Wouter Swierstra and Alejandro Serrano 1 Program Correctness 2 Testing and correctness When is a program correct? 3 Testing and correctness When is a

More information

Program Calculus Calculational Programming

Program 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 information

FUNCTIONAL PEARLS The countdown problem

FUNCTIONAL PEARLS The countdown problem To appear in the Journal of Functional Programming 1 FUNCTIONAL PEARLS The countdown problem GRAHAM HUTTON School of Computer Science and IT University of Nottingham, Nottingham, UK www.cs.nott.ac.uk/

More information

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions 0 Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x 2 x {1...5}} The set {1,4,9,16,25}

More information

Introduction to Homotopy Type Theory

Introduction to Homotopy Type Theory Introduction to Homotopy Type Theory Lecture notes for a course at EWSCS 2017 Thorsten Altenkirch March 5, 2017 1 What is this course about? To explain what Homotopy Type Theory is, I will first talk about

More information

Software Properties as Axioms and Theorems

Software Properties as Axioms and Theorems Applied Software Properties as Axioms and Theorems proofs by induction or How to Write Reliable Software and know it's reliable Applied 1 Example: Multiplexor Function Problem: Multiplex two sequences

More information

Fall Recursion and induction. Stephen Brookes. Lecture 4

Fall 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 information

COMPUTER SCIENCE TRIPOS

COMPUTER SCIENCE TRIPOS CST.0.. COMPUTER SCIENCE TRIPOS Part IA NATURAL SCIENCES TRIPOS Part IA (Paper CS/) POLITICS, PSYCHOLOGY, AND SOCIOLOGY TRIPOS Part I (Paper 9) Monday June 0.0 to 4.0 COMPUTER SCIENCE Paper Answer five

More information

Haskell Overview III (3A) Young Won Lim 10/4/16

Haskell Overview III (3A) Young Won Lim 10/4/16 (3A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions

More information

Figure 4.1: The evolution of a rooted tree.

Figure 4.1: The evolution of a rooted tree. 106 CHAPTER 4. INDUCTION, RECURSION AND RECURRENCES 4.6 Rooted Trees 4.6.1 The idea of a rooted tree We talked about how a tree diagram helps us visualize merge sort or other divide and conquer algorithms.

More information

Logic - CM0845 Introduction to Haskell

Logic - CM0845 Introduction to Haskell Logic - CM0845 Introduction to Haskell Diego Alejandro Montoya-Zapata EAFIT University Semester 2016-1 Diego Alejandro Montoya-Zapata (EAFIT University) Logic - CM0845 Introduction to Haskell Semester

More information

Logic and Computation Lecture 20 CSU 290 Spring 2009 (Pucella) Thursday, Mar 12, 2009

Logic and Computation Lecture 20 CSU 290 Spring 2009 (Pucella) Thursday, Mar 12, 2009 Logic and Computation Lecture 20 CSU 290 Spring 2009 (Pucella) Thursday, Mar 12, 2009 Note that I change the name of the functions slightly in these notes from what I used in class, to be consistent with

More information

CSE341 Spring 2017, Midterm Examination April 28, 2017

CSE341 Spring 2017, Midterm Examination April 28, 2017 CSE341 Spring 2017, Midterm Examination April 28, 2017 Please do not turn the page until 12:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please

More information

Computer Science 236 Fall Nov. 11, 2010

Computer Science 236 Fall Nov. 11, 2010 Computer Science 26 Fall Nov 11, 2010 St George Campus University of Toronto Assignment Due Date: 2nd December, 2010 1 (10 marks) Assume that you are given a file of arbitrary length that contains student

More information

Lecture 19: Functions, Types and Data Structures in Haskell

Lecture 19: Functions, Types and Data Structures in Haskell The University of North Carolina at Chapel Hill Spring 2002 Lecture 19: Functions, Types and Data Structures in Haskell Feb 25 1 Functions Functions are the most important kind of value in functional programming

More information

Informatics 1 Functional Programming Lecture 4. Lists and Recursion. Don Sannella University of Edinburgh

Informatics 1 Functional Programming Lecture 4. Lists and Recursion. Don Sannella University of Edinburgh Informatics 1 Functional Programming Lecture 4 Lists and Recursion Don Sannella University of Edinburgh Part I Lists and Recursion Cons and append Cons takes an element and a list. Append takes two lists.

More information

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

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors Solution sheet 1 Introduction Please note that there can be other solutions than those listed in this document. This is a literate Haskell file which is available as PDF, as well as literate Haskell source

More information

Efficient Mergesort. Christian Sternagel. August 28, 2014

Efficient Mergesort. Christian Sternagel. August 28, 2014 Efficient Mergesort Christian Sternagel August 28, 2014 Abstract We provide a formalization of the mergesort algorithm as used in GHC s Data.List module, proving correctness and stability. Furthermore,

More information

Sorting. Weiss chapter , 8.6

Sorting. Weiss chapter , 8.6 Sorting Weiss chapter 8.1 8.3, 8.6 Sorting 5 3 9 2 8 7 3 2 1 4 1 2 2 3 3 4 5 7 8 9 Very many different sorting algorithms (bubblesort, insertion sort, selection sort, quicksort, heapsort, mergesort, shell

More information

School of Computer Science

School of Computer Science A27217 No calculator permitted in this examination School of Computer Science First Year - BSc Artificial Intelligence and Computer Science First Year - BSc Natural Sciences First Year - BSc Computer Science

More information

CS 457/557: Functional Languages

CS 457/557: Functional Languages CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University 1 Why Lists? Lists are a heavily used data structure in many functional programs Special syntax is

More information

CSE-321 Programming Languages 2012 Midterm

CSE-321 Programming Languages 2012 Midterm Name: Hemos ID: CSE-321 Programming Languages 2012 Midterm Prob 1 Prob 2 Prob 3 Prob 4 Prob 5 Prob 6 Total Score Max 14 15 29 20 7 15 100 There are six problems on 24 pages in this exam. The maximum score

More information

Lists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca

Lists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca Lists Adrian Groza Department of Computer Science Technical University of Cluj-Napoca Recall... Parameter evaluation Call-by-value Call-by-name Call-by-need Functions Infix operators Local declarations,

More information

A general introduction to Functional Programming using Haskell

A general introduction to Functional Programming using Haskell A general introduction to Functional Programming using Haskell Matteo Rossi Dipartimento di Elettronica e Informazione Politecnico di Milano rossi@elet.polimi.it 1 Functional programming in a nutshell

More information

Mini-ML. CS 502 Lecture 2 8/28/08

Mini-ML. CS 502 Lecture 2 8/28/08 Mini-ML CS 502 Lecture 2 8/28/08 ML This course focuses on compilation techniques for functional languages Programs expressed in Standard ML Mini-ML (the source language) is an expressive core subset of

More information

Programming in Omega Part 1. Tim Sheard Portland State University

Programming in Omega Part 1. Tim Sheard Portland State University Programming in Omega Part 1 Tim Sheard Portland State University Tim Sheard Computer Science Department Portland State University Portland, Oregon PSU PL Research at Portland State University The Programming

More information

Topic 5: Examples and higher-order functions

Topic 5: Examples and higher-order functions CITS 3242 Programming Paradigms Topic 5: Examples and higher-order functions This lecture includes some larger examples in F# and introduces higher-functions. 1 Examples: append Now that we have lists,

More information

Final Examination: Topics and Sample Problems

Final 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 information

1. Find f(1), f(2), f(3), and f(4) if f(n) is defined recursively by f(0) = 1 and for n = 0, 1, 2,

1. Find f(1), f(2), f(3), and f(4) if f(n) is defined recursively by f(0) = 1 and for n = 0, 1, 2, Exercises Exercises 1. Find f(1), f(2), f(3), and f(4) if f(n) is defined recursively by f(0) = 1 and for n = 0, 1, 2, a) f(n + 1) = f(n) + 2. b) f(n + 1) = 3f(n). c) f(n + 1) = 2f(n). d) f(n + 1) = f(n)2

More information

CS 440: Programming Languages and Translators, Spring 2019 Mon

CS 440: Programming Languages and Translators, Spring 2019 Mon Haskell, Part 4 CS 440: Programming Languages and Translators, Spring 2019 Mon 2019-01-28 More Haskell Review definition by cases Chapter 6: Higher-order functions Revisit currying map, filter Unnamed

More information

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

More information

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

Advanced features of Functional Programming (Haskell)

Advanced features of Functional Programming (Haskell) Advanced features of Functional Programming (Haskell) Polymorphism and overloading January 10, 2017 Monomorphic and polymorphic types A (data) type specifies a set of values. Examples: Bool: the type of

More information

Exercise 1: Graph coloring (10 points)

Exercise 1: Graph coloring (10 points) Exercise 1: Graph coloring (10 points) Graph coloring is the problem of assigning colors to vertices in a non-directed graph, so that no two adjacent nodes have the same color. In other words, if two vertices

More information

MC 302 GRAPH THEORY 10/1/13 Solutions to HW #2 50 points + 6 XC points

MC 302 GRAPH THEORY 10/1/13 Solutions to HW #2 50 points + 6 XC points MC 0 GRAPH THEORY 0// Solutions to HW # 0 points + XC points ) [CH] p.,..7. This problem introduces an important class of graphs called the hypercubes or k-cubes, Q, Q, Q, etc. I suggest that before you

More information

Thinking Induc,vely. COS 326 David Walker Princeton University

Thinking Induc,vely. COS 326 David Walker Princeton University Thinking Induc,vely COS 326 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa,onal purposes Administra,on 2 Assignment

More information

Programming Paradigms Written Exam (6 CPs)

Programming Paradigms Written Exam (6 CPs) Programming Paradigms Written Exam (6 CPs) 22.06.2017 First name Student number Last name Signature Instructions for Students Write your name and student number on the exam sheet and on every solution

More information

Recursion. Tracing Method Calls via a Stack. Beyond this lecture...

Recursion. Tracing Method Calls via a Stack. Beyond this lecture... Recursion EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

F28PL1 Programming Languages. Lecture 14: Standard ML 4

F28PL1 Programming Languages. Lecture 14: Standard ML 4 F28PL1 Programming Languages Lecture 14: Standard ML 4 Polymorphic list operations length of list base case: [] ==> 0 recursion case: (h::t) => 1 more than length of t - fun length [] = 0 length (_::t)

More information

AXIOMS FOR THE INTEGERS

AXIOMS FOR THE INTEGERS AXIOMS FOR THE INTEGERS BRIAN OSSERMAN We describe the set of axioms for the integers which we will use in the class. The axioms are almost the same as what is presented in Appendix A of the textbook,

More information

CSE 20 DISCRETE MATH WINTER

CSE 20 DISCRETE MATH WINTER CSE 20 DISCRETE MATH WINTER 2016 http://cseweb.ucsd.edu/classes/wi16/cse20-ab/ Today's learning goals Explain the steps in a proof by (strong) mathematical induction Use (strong) mathematical induction

More information

INF2220: algorithms and data structures Series 1

INF2220: algorithms and data structures Series 1 Universitetet i Oslo Institutt for Informatikk A. Maus, R.K. Runde, I. Yu INF2220: algorithms and data structures Series 1 Topic Trees & estimation of running time (Exercises with hints for solution) Issued:

More information

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial: Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Factorial (1) Recall the formal definition of calculating the n factorial: 1 if n = 0 n! = n (n 1) (n 2) 3 2

More information

Lamé s Theorem. Strings. Recursively Defined Sets and Structures. Recursively Defined Sets and Structures

Lamé s Theorem. Strings. Recursively Defined Sets and Structures. Recursively Defined Sets and Structures Lamé s Theorem Gabriel Lamé (1795-1870) Recursively Defined Sets and Structures Lamé s Theorem: Let a and b be positive integers with a b Then the number of divisions used by the Euclidian algorithm to

More information

301AA - Advanced Programming

301AA - Advanced Programming 301AA - Advanced Programming Lecturer: Andrea Corradini andrea@di.unipi.it h;p://pages.di.unipi.it/corradini/ Course pages: h;p://pages.di.unipi.it/corradini/dida@ca/ap-18/ AP-2018-19: Algebraic Datatypes

More information

CS 321 Programming Languages

CS 321 Programming Languages CS 321 Programming Languages Intro to OCaml Lists Baris Aktemur Özyeğin University Last update made on Monday 2 nd October, 2017 at 19:27. Some of the contents here are taken from Elsa Gunter and Sam Kamin

More information

Mathematically Rigorous Software Design Review of mathematical prerequisites

Mathematically Rigorous Software Design Review of mathematical prerequisites Mathematically Rigorous Software Design 2002 September 27 Part 1: Boolean algebra 1. Define the Boolean functions and, or, not, implication ( ), equivalence ( ) and equals (=) by truth tables. 2. In an

More information

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). Working with recursion Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). We can extend the idea of a self-referential definition to defining the natural numbers, which leads to the use of recursion in

More information

Working with recursion

Working with recursion Working with recursion Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). We can extend the idea of a self-referential definition to defining the natural numbers, which leads to the use of recursion in

More information

CSCI-GA Final Exam

CSCI-GA Final Exam CSCI-GA 2110-003 - Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly

More information

Efficient Mergesort. Christian Sternagel. October 11, 2017

Efficient Mergesort. Christian Sternagel. October 11, 2017 Efficient Mergesort Christian Sternagel October 11, 2017 Abstract We provide a formalization of the mergesort algorithm as used in GHC s Data.List module, proving correctness and stability. Furthermore,

More information

Handout 9: Imperative Programs and State

Handout 9: Imperative Programs and State 06-02552 Princ. of Progr. Languages (and Extended ) The University of Birmingham Spring Semester 2016-17 School of Computer Science c Uday Reddy2016-17 Handout 9: Imperative Programs and State Imperative

More information

Chapter 3 Linear Structures: Lists

Chapter 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 information

Chapter 6 Abstract Datatypes

Chapter 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 information

Sets. Sets. Subset, universe. Specifying sets, membership. Examples: Specifying a set using a predicate. Examples

Sets. Sets. Subset, universe. Specifying sets, membership. Examples: Specifying a set using a predicate. Examples Sets 2/36 We will not give a precise definition of what is a set, but we will say precisely what you can do with it. Sets Lectures 7 and 8 (hapter 16) (Think of a set as a collection of things of which

More information

Case-Analysis for Rippling and Inductive Proof

Case-Analysis for Rippling and Inductive Proof Case-Analysis for Rippling and Inductive Proof Moa Johansson 1 Joint work with Lucas Dixon 2 and Alan Bundy 2 Dipartimento di Informatica, Università degli Studi di Verona, Italy. 1 School of Informatics,

More information

Exercise 1 (2+2+2 points)

Exercise 1 (2+2+2 points) 1 Exercise 1 (2+2+2 points) The following data structure represents binary trees only containing values in the inner nodes: data Tree a = Leaf Node (Tree a) a (Tree a) 1 Consider the tree t of integers

More information

UNIVERSITY OF EDINBURGH COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS INFR08025 INFORMATICS 1 - INTRODUCTION TO COMPUTATION

UNIVERSITY OF EDINBURGH COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS INFR08025 INFORMATICS 1 - INTRODUCTION TO COMPUTATION UNIVERSITY OF EDINBURGH COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS INFR08025 INFORMATICS 1 - INTRODUCTION TO COMPUTATION Thursday 13 th December 2018 14:30 to 16:30 INSTRUCTIONS TO CANDIDATES

More information

1 Problem Description

1 Problem Description Tree Isomorphism: An Exercise in Functional Programming Jayadev Misra 9/10/01 1 Problem Description The problem is to decide if two unordered trees are the same. More precisely, define a binary relation

More information

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination University of Illinois at Urbana-Champaign Department of Computer Science Second Examination CS 225 Data Structures and Software Principles Spring 2014 7-10p, Tuesday, April 8 Name: NetID: Lab Section

More information