C. Varela; Adapted w. permission from S. Haridi and P. Van Roy1 Functional Programming: Lists, Pattern Matching, Recursive Programming (CTM Sections 1.1-1.7,

Slides:



Advertisements
Similar presentations
MATH 224 – Discrete Mathematics
Advertisements

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Programming Techniques Accumulators, Difference Lists (VRH ) Carlos Varela.
C. Varela; Adapted from S. Haridi and P. Van Roy1 Declarative Programming Techniques Lazy Execution (VRH 4.5) Carlos Varela RPI Adapted with permission.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Computation Model From kernel to practical language (CTM 2.6) Exceptions (CTM.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Computation Model Defining practical programming languages Carlos Varela RPI.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Computation Model Memory management, Exceptions, From kernel to practical language.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Computation Model Single assignment store Kernel language syntax Carlos Varela.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Data Abstraction and State Abstract Data Types (3.7) State/Data Abstraction(6.1, 6.3, 6.4.1,
C. Varela; Adapted w. permission from S. Haridi and P. Van Roy1 Introduction to Programming Concepts Carlos Varela RPI Adapted with permission from: Seif.
6.001 SICP SICP – September ? 6001-Introduction Trevor Darrell 32-D web page: section.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Computation Model Kernel language semantics Carlos Varela RPI Adapted with permission.
Recursive Algorithms Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
מבוא מורחב 1 Lecture 3 Material in the textbook Sections to
מבוא מורחב - שיעור 2 1 Lecture 2 - Substitution Model (continued) - Recursion - Block structure and scope (if time permits)
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Computation Model Memory management, Exceptions, From kernel to practical language.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Programming Techniques Non-declarative needs (VRH 3.8) Program design in the.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Programming Techniques Declarativeness, iterative computation (VRH 3.1-2) Higher-order.
Section Section Summary Recursive Algorithms Proving Recursive Algorithms Correct Recursion and Iteration (not yet included in overheads) Merge.
Induction and recursion
February 17, 2015Applied Discrete Mathematics Week 3: Algorithms 1 Double Summations Table 2 in 4 th Edition: Section th Edition: Section th.
Exercise problems for students taking the Programming Parallel Computers course. Janusz Kowalik Piotr Arlukowicz Tadeusz Puzniakowski Informatics Institute.
CS10 Final Review by Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.Glenn Sugdenmons Attribution-NonCommercial-ShareAlike.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Computation Model Memory management (CTM 2.5) Carlos Varela RPI April 6, 2015.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
מבוא מורחב 1 Review: scheme language things that make up scheme programs: self-evaluating 23, "hello", #t names +, pi combinations (+ 2 3) (* pi 4) special.
Fall 2002CMSC Discrete Structures1 Enough Mathematical Appetizers! Let us look at something more interesting: Algorithms.
Major objective of this course is: Design and analysis of modern algorithms Different variants Accuracy Efficiency Comparing efficiencies Motivation thinking.
CSC 211 Data Structures Lecture 13
C. Varela1 Programming Languages (CSCI 4430/6430) Part 1: Functional Programming: Summary Carlos Varela Rennselaer Polytechnic Institute September 29,
1 The Evaluator. 2 Compiler vs. Interpreter Command Processing Unit The Computer Program in Low Level Machine Language Program in High Level Language.
11/23/2015CS2104, Lecture 41 Programming Language Concepts, COSC Lecture 4 Procedures, last call optimization.
Principles Of Programming Languages Lecture 2 Today Design-By-Contract Iteration vs. Recursion If we have time: live demo!!!
S. Haridi and P. Van Roy1 Introduction to Programming Seif Haridi KTH Peter Van Roy UCL.
CS220 Programming Principles 프로그래밍의 이해 2003 가을학기 Class 2 한 태숙.
C. Varela1 Logic Programming (CTM ) Constraint Programming: Constraints and Computation Spaces Carlos Varela Rennselaer Polytechnic Institute.
2.6 APPLICATIONS OF INDUCTION & OTHER IDEAS IMPORTANT THEOREMS MIDWESTERN STATE UNIVERSITY – COMPUTER SCIENCE.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Higher-Order Programming: Iterative computation (CTM Section 3
CS314 – Section 5 Recitation 9
Advanced Algorithms Analysis and Design
Chapter 9: Value-Returning Functions
Applied Discrete Mathematics Week 2: Functions and Sequences
Functional Programming: Lists, Pattern Matching, Recursive Programming (CTM Sections , 3.2, , 4.7.2) Carlos Varela RPI September 12,
Carlos Varela Rennselaer Polytechnic Institute September 27, 2016
CS 326 Programming Languages, Concepts and Implementation
Computing Square Roots
A lightening tour in 45 minutes
Higher-Order Programming: Iterative computation (CTM Section 3
Carlos Varela RPI September 22, 2017 Adapted with permission from:
Declarative Programming Techniques Accumulators (CTM 3. 4
Enough Mathematical Appetizers!
Declarative Computation Model Kernel language semantics (Non-)Suspendable statements (VRH ) Carlos Varela RPI October 11, 2007 Adapted with.
Computation.
Declarative Programming Techniques Declarativeness, iterative computation (CTM ) Higher-order programming (CTM 3.6) Abstract data types (CTM.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
6.001 SICP Data abstractions
Algorithm An algorithm is a finite set of steps required to solve a problem. An algorithm must have following properties: Input: An algorithm must have.
Objective of This Course
Applied Discrete Mathematics Week 6: Computation
Higher-Order Programming: Closures, procedural abstraction, genericity, instantiation, embedding. Control abstractions: iterate, map, reduce, fold, filter.
Declarative Programming Techniques Accumulators (CTM 3. 4
Introduction to Programming Concepts (VRH )
Declarative Computation Model Single assignment store (VRH 2
Enough Mathematical Appetizers!
Introduction to Programming Concepts
Enough Mathematical Appetizers!
Declarative Programming Techniques Accumulators (CTM 3. 4
Presentation transcript:

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy1 Functional Programming: Lists, Pattern Matching, Recursive Programming (CTM Sections , 3.2, ,4.7.2) Carlos Varela RPI September 11, 2015 Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy2 Introduction to Oz An introduction to programming concepts Declarative variables Structured data (example: lists) Functions over lists Correctness and complexity

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy3 Variables Variables are short-cuts for values, they cannot be assigned more than once declare V = 9999*9999 {Browse V*V} Variable identifiers: is what you type Store variable: is part of the memory system The declare statement creates a store variable and assigns its memory address to the identifier ’ V ’ in the environment

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy4 Functions Compute the factorial function: Start with the mathematical definition declare fun {Fact N} if N==0 then 1 else N*{Fact N-1} end end Fact is declared in the environment Try large factorial {Browse {Fact 100}}

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy5 Factorial in Haskell factorial :: Integer -> Integer factorial 0= 1 factorial n | n > 0= n * factorial (n-1)

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy6 Composing functions Combinations of r items taken from n. The number of subsets of size r taken from a set of size n declare fun {Comb N R} {Fact N} div ({Fact R}*{Fact N-R}) end Example of functional abstraction Comb Fact

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy7 Structured data (lists) Calculate Pascal triangle Write a function that calculates the nth row as one structured value A list is a sequence of elements: [ ] The empty list is written nil Lists are created by means of ”|” (cons) declare H=1 T = [ ] {Browse H|T} % This will show [ ]

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy8 Lists (2) Taking lists apart (selecting components) A cons has two components: a head, and a tail declare L = [ ] L.1 gives 5 L.2 give [6 7 8] ‘|’‘|’ ‘|’‘|’ ‘|’‘|’ 6 7 8nil

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy9 Pattern matching Another way to take a list apart is by use of pattern matching with a case instruction case L of H|T then {Browse H} {Browse T} else {Browse ‘empty list’} end

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy10 Functions over lists Compute the function {Pascal N} Takes an integer N, and returns the Nth row of a Pascal triangle as a list 1.For row 1, the result is [1] 2.For row N, shift to left row N-1 and shift to the right row N-1 3.Align and add the shifted rows element-wise to get row N (0) [ ] [ ] Shift right Shift left

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy11 Functions over lists (2) declare fun {Pascal N} if N==1 then [1] else {AddList {ShiftLeft {Pascal N-1}} {ShiftRight {Pascal N-1}}} end AddList ShiftLeftShiftRight Pascal N-1 Pascal N

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy12 Functions over lists (3) fun {ShiftLeft L} case L of H|T then H|{ShiftLeft T} else [0] end fun {ShiftRight L} 0|L end fun {AddList L1 L2} case L1 of H1|T1 then case L2 of H2|T2 then H1+H2|{AddList T1 T2} end else nil end end

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy13 Top-down program development Understand how to solve the problem by hand Try to solve the task by decomposing it to simpler tasks Devise the main function (main task) in terms of suitable auxiliary functions (subtasks) that simplify the solution ( ShiftLeft, ShiftRight and AddList ) Complete the solution by writing the auxiliary functions Test your program bottom-up: auxiliary functions first.

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy14 Is your program correct? “A program is correct when it does what we would like it to do” In general we need to reason about the program: Semantics for the language: a precise model of the operations of the programming language Program specification: a definition of the output in terms of the input (usually a mathematical function or relation) Use mathematical techniques to reason about the program, using programming language semantics

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy15 Mathematical induction Select one or more inputs to the function Show the program is correct for the simple cases (base cases) Show that if the program is correct for a given case, it is then correct for the next case. For natural numbers, the base case is either 0 or 1, and for any number n the next case is n+1 For lists, the base case is nil, or a list with one or a few elements, and for any list T the next case is H|T

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy16 Correctness of factorial fun {Fact N} if N==0 then 1 else N*{Fact N-1} end end Base Case N=0: {Fact 0} returns 1 Inductive Case N>0: {Fact N} returns N*{Fact N-1} assume {Fact N-1} is correct, from the spec we see that {Fact N} is N*{Fact N-1}

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy17 Complexity Pascal runs very slow, try {Pascal 24} {Pascal 20} calls: {Pascal 19} twice, {Pascal 18} four times, {Pascal 17} eight times,..., {Pascal 1} 2 19 times Execution time of a program up to a constant factor is called the program’s time complexity. Time complexity of {Pascal N} is proportional to 2 N (exponential) Programs with exponential time complexity are impractical declare fun {Pascal N} if N==1 then [1] else {AddList {ShiftLeft {Pascal N-1}} {ShiftRight {Pascal N-1}}} end

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy18 fun {FastPascal N} if N==1 then [1] else local L in L={FastPascal N-1} {AddList {ShiftLeft L} {ShiftRight L}} end Faster Pascal Introduce a local variable L Compute {FastPascal N-1} only once Try with 30 rows. FastPascal is called N times, each time a list on the average of size N/2 is processed The time complexity is proportional to N 2 (polynomial) Low order polynomial programs are practical.

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy19 Iterative computation An iterative computation is one whose execution stack is bounded by a constant, independent of the length of the computation Iterative computation starts with an initial state S 0, and transforms the state in a number of steps until a final state S final is reached:

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy20 The general scheme fun {Iterate S i } if {IsDone S i } then S i else S i+1 in S i+1 = {Transform S i } {Iterate S i+1 } end IsDone and Transform are problem dependent

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy21 The computation model STACK : [ R={Iterate S 0 }] STACK : [ S 1 = {Transform S 0 }, R={Iterate S 1 } ] STACK : [ R={Iterate S i }] STACK : [ S i+1 = {Transform S i }, R={Iterate S i+1 } ] STACK : [ R={Iterate S i+1 }]

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy22 Newton’s method for the square root of a positive real number Given a real number x, start with a guess g, and improve this guess iteratively until it is accurate enough The improved guess g’ is the average of g and x/g:

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy23 Newton’s method for the square root of a positive real number Given a real number x, start with a guess g, and improve this guess iteratively until it is accurate enough The improved guess g’ is the average of g and x/g: Accurate enough is defined as: | x – g 2 | / x <

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy24 SqrtIter fun {SqrtIter Guess X} if {GoodEnough Guess X} then Guess else Guess1 = {Improve Guess X} in {SqrtIter Guess1 X} end Compare to the general scheme: –The state is the pair Guess and X –IsDone is implemented by the procedure GoodEnough –Transform is implemented by the procedure Improve

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy25 The program version 1 fun {Sqrt X} Guess = 1.0 in {SqrtIter Guess X} end fun {SqrtIter Guess X} if {GoodEnough Guess X} then Guess else {SqrtIter {Improve Guess X} X} end fun {Improve Guess X} (Guess + X/Guess)/2.0 end fun {GoodEnough Guess X} {Abs X - Guess*Guess}/X < end

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy26 Using local procedures The main procedure Sqrt uses the helper procedures SqrtIter, GoodEnough, Improve, and Abs SqrtIter is only needed inside Sqrt GoodEnough and Improve are only needed inside SqrtIter Abs (absolute value) is a general utility The general idea is that helper procedures should not be visible globally, but only locally

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy27 Sqrt version 2 local fun {SqrtIter Guess X} if {GoodEnough Guess X} then Guess else {SqrtIter {Improve Guess X} X} end end fun {Improve Guess X} (Guess + X/Guess)/2.0 end fun {GoodEnough Guess X} {Abs X - Guess*Guess}/X < end in fun {Sqrt X} Guess = 1.0 in {SqrtIter Guess X} end end

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy28 Sqrt version 3 Define GoodEnough and Improve inside SqrtIter local fun {SqrtIter Guess X} fun {Improve} (Guess + X/Guess)/2.0 end fun {GoodEnough} {Abs X - Guess*Guess}/X < end in if {GoodEnough} then Guess else {SqrtIter {Improve} X} end end in fun {Sqrt X} Guess = 1.0 in {SqrtIter Guess X} end

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy29 Sqrt version 3 Define GoodEnough and Improve inside SqrtIter local fun {SqrtIter Guess X} fun {Improve} (Guess + X/Guess)/2.0 end fun {GoodEnough} {Abs X - Guess*Guess}/X < end in if {GoodEnough} then Guess else {SqrtIter {Improve} X} end end in fun {Sqrt X} Guess = 1.0 in {SqrtIter Guess X} end The program has a single drawback: on each iteration two procedure values are created, one for Improve and one for GoodEnough

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy30 Sqrt final version fun {Sqrt X} fun {Improve Guess} (Guess + X/Guess)/2.0 end fun {GoodEnough Guess} {Abs X - Guess*Guess}/X < end fun {SqrtIter Guess} if {GoodEnough Guess} then Guess else {SqrtIter {Improve Guess} } end end Guess = 1.0 in {SqrtIter Guess} end The final version is a compromise between abstraction and efficiency

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy31 From a general scheme to a control abstraction (1) fun {Iterate S i } if {IsDone S i } then S i else S i+1 in S i+1 = {Transform S i } {Iterate S i+1 } end IsDone and Transform are problem dependent

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy32 From a general scheme to a control abstraction (2) fun {Iterate S IsDone Transform} if {IsDone S} then S else S1 in S1 = {Transform S} {Iterate S1 IsDone Transform} end fun {Iterate S i } if {IsDone S i } then S i else S i+1 in S i+1 = {Transform S i } {Iterate S i+1 } end

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy33 Sqrt using the Iterate abstraction fun {Sqrt X} fun {Improve Guess} (Guess + X/Guess)/2.0 end fun {GoodEnough Guess} {Abs X - Guess*Guess}/X < end Guess = 1.0 in {Iterate Guess GoodEnough Improve} end

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy34 Sqrt using the control abstraction fun {Sqrt X} {Iterate 1.0 fun {$ G} {Abs X - G*G}/X < end fun {$ G} (G + X/G)/2.0 end } end Iterate could become a linguistic abstraction

C. Varela; Adapted w/permission from S. Haridi and P. Van Roy35 Sqrt in Haskell let sqrt x = head (dropWhile (not. goodEnough) sqrtGuesses) where goodEnough guess = (abs (x – guess*guess))/x < improve guess = (guess + x/guess)/2.0 sqrtGuesses = 1:(map improve sqrtGuesses)

C. Varela; Adapted w. permission from S. Haridi and P. Van Roy36 Exercises 12.Prove the correctness of AddList and ShiftLeft. 13.Prove that the alternative version of Pascal triangle (not using ShiftLeft) is correct. Make AddList and OpList commutative. 14.Modify the Pascal function to use local functions for AddList, ShiftLeft, ShiftRight. Think about the abstraction and efficiency tradeoffs. 15.CTM Exercise (page 230) 16.CTM Exercise (page 230) 17.Develop a control abstraction for iterating over a list of elements.