Com2010 - Functional Programming Higher Order Functions and Computation Patterns (II) Marian Gheorghe Lecture 11 Module homepage Mole &

Slides:



Advertisements
Similar presentations
Introduction to Recursion and Recursive Algorithms
Advertisements

Com Functional Programming Algebraic Data Types Marian Gheorghe Lecture 12 Module homepage Mole & ©University of.
Recursion.
More on Recursive Methods KFUPM- ICS Data Structures.
Recursion. Binary search example postponed to end of lecture.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursive Algorithms Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Fundamentals of Python: From First Programs Through Data Structures
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 4. Outline High order procedures –Finding Roots –Compose Functions Accelerating Computations –Fibonacci 2.
Com1040 Systems Design and Testing Part II – Testing (Based on A.J. Cowling’s lecture notes) LN-Test3: Equivalence classes and boundary conditions Marian.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Com Functional Programming Higher Order Functions and Computation Patterns (I) Marian Gheorghe Lecture 10 Module homepage Mole &
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
M180: Data Structures & Algorithms in Java
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
Data Structures and Algorithms Stacks. Stacks are a special form of collection with LIFO semantics Two methods int push( Stack s, void *item ); - add.
Chapter 8 Recursion Modified.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Com Functional Programming Regular Expressions and Abstract Data Types Marian Gheorghe Lecture 14 Module homepage Mole &
Lecture 7. Solution by Substitution Method T(n) = 2 T(n/2) + n Substitute n/2 into the main equation 2T(n/2) = 2(2(T(n/4)) + n/2) = 4T(n/4) + n And T(n)
Com Functional Programming Lazy Evaluation Marian Gheorghe Lecture 13 Module homepage Mole & ©University of Sheffieldcom2010.
Recursion Unit 15. Recursion: Recursion is defined as the process of a subprogram calling itself as part of the solution to a problem. It is a problem.
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
1 Dynamic Programming Topic 07 Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing Lab. School of Information and Computer Technology.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
Fundamentals of Python: First Programs Chapter 6: Design with Functions.
Ramamurthy Recursion: The Mirrors B. Ramamurthy CS114A,B.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 3. Outline High order procedures –Finding Roots –Compose Functions Accelerating Computations –Fibonacci 2.
1 Recursion. 2 A process by which a function calls itself repeatedly  Either directly. X calls X  Or cyclically in a chain. X calls Y, and Y calls X.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Advanced Algorithms Analysis and Design By Dr. Nazir Ahmad Zafar Dr Nazir A. Zafar Advanced Algorithms Analysis and Design.
Recursion.
Recursion.
Recursion Version 1.0.
Recursion DRILL: Please take out your notes on Recursion
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Lesson #6 Modular Programming and Functions.
Lecture 16 Streams continue Infinite Streams מבוא מורחב - שיעור 16.
Lesson #6 Modular Programming and Functions.
Towers of Hanoi Move n (4) disks from pole A to pole C
COMP108 Algorithmic Foundations Divide and Conquer
CS 326 Programming Languages, Concepts and Implementation
More on Recursive Methods
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Closures and Streams cs784(Prasad) L11Clos
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Algorithm Analysis (for Divide-and-Conquer problems)
Stacks & Recursion.
CS201: Data Structures and Discrete Mathematics I
Recursion.
Unit 3 Test: Friday.
PROGRAMMING IN HASKELL
Lecture 2 מבוא מורחב.
Lecture 2 מבוא מורחב.
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Com Functional Programming Higher Order Functions and Computation Patterns (II) Marian Gheorghe Lecture 11 Module homepage Mole & ©University of Sheffieldcom2010

18. Higher-Order Functions and Computation Patterns 18.3 … primitive recursion 18.4 Efficiency and recursion patterns 18.5 Partial functions and errors 18.6 More higher-order on lists Summary ©University of Sheffieldcom2010

Iterations of different functions: f_1, f_2, …,f_n Example. The function fact(n) = n! may be obtained as 1  *2  2  *3 …  *n  n! or similar to get [1, 2, …, n] Obs. At step n we multiply by n or append n to the list. fact :: Int -> Int -- construct n! fact n | n == 0 = 1 | n > 0 = fact(n-1) * n natList :: Int -> [Int] -- constructs seq of naturals natList n | n == 0 = [] | n > 0 = natList (n-1) ++ [n] Primitive recursion - example ©University of Sheffieldcom2010

The pattern of primitive recursion: primRec::(Int->a->a)->a->Int->a -- 1st param: iter function, depends on iteration stage -- 2nd param: initial value -- 3rd param: iteration length primRec f x n | n==0 = x | n>0 = f n (primRec f x (n-1)) Examples myFact :: Int ->Int myFact = primRec (\n x -> x*n) 1 myNatList ::Int -> [Int] myNatList = primRec (\n x -> x++[n]) [] Primitive recursion - pattern ©University of Sheffieldcom2010

Fibonacci sequence: fib :: Int -> Int – nice, simple, but inefficient (exp in n) fib n | n == 0 = 0 | n == 1 = 1 | n > 1 = fib(n-2) + fib(n-1) Fibonacci sequence; efficient version fibNextStep :: (Int, Int) -> (Int, Int) fibNextStep (x, y) = (y, x + y) -- uses myIter iteration function; efficient (linear in n) fastFib :: (Int -> Int) -- fast Fibonacci sequence fastFib = fst. (myIter fibNextStep (0,1)) Run fib, fastFib for 30 and watch the time !! Efficiency of recursion patterns ©University of Sheffieldcom2010

Iteration and primitive recursion are two general powerful elegant abstract mechanisms When fast algorithms are requested then less general solutions may be more efficient Ex: fib 20 makes reductions Whereas fastfib 20 makes 417 reduction Generality vs efficiency ©University of Sheffieldcom2010

Simple examples include attempts to divide by 0, to take the square root of a negative number, or the head of an empty list. applying a function defined by (primitive) recursion on natural numbers to negative numbers (fib(-2)). applying a function to an input value that is not caught by any pattern or guard in any of the function's definition equations (non- exhaustive patterns or guards). A hierarchy of` error treatment is studied Partial functions and errors ©University of Sheffieldcom2010

The function definition naiveFib :: Int -> In -- may loop naiveFib 0 = 0 naiveFib 1 = 1 naiveFib n = naiveFib(n-1) + naiveFib(n-2) When execute naiveFib with argument -3, naiveFib (-3) Error: control stack overflow!! fib :: Int -> Int -- may show run-time error fib 0 = 0 fib 1 = 1 fib n | n > 1 = fib(n-1) + fib(n-2) Run-time error when a value outside the range is used Errors: infinite loops; missing condition ©University of Sheffieldcom2010

A simple example using error built-in function newFib :: Int -> Int -- may produce error message newFib 0 = 0 newFib 1 = 1 newFib n | n > 1 = newFib(n-1) + newFib(n-2) | otherwise = error( "\nError in newFib:Fibonacci " ++"function cannot \nbe applied to" ++" negative integer “ ++show(n) ++"\n") When newFib (-3) is used then an error will be displayed Program abortion ©University of Sheffieldcom2010

Exceptional inputs can be covered by defining natural dummy results. Consider the Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, … again. It would appear natural to extend the sequence into the negative indices by repeating 0 : …, 0, 0, 0, 0, 1, 1, 2, 3, 5, 8, … i.e. we define fib n = 0, for negative n. So, 0 would be the dummy result for negative inputs. This would give us the following implementation: extFib :: Int -> Int -- extends 0's leftwards extFib 0 = 0 extFib 1 = 1 extFib n | n > 1 = extFib(n-1) + extFib(n-2) | otherwise = 0 Dummy values (1) ©University of Sheffieldcom2010

A better variant using dummy values symFib :: Int -> Int -- satisfies recursion law symFib 0 = 0 symFib 1 = 1 symFib n | n > 1 = symFib(n-1) + symFib(n-2) | otherwise = symFib(n+2) - symFib(n+1) SymFib(-1)=1, symFib(-2)=-1, SymFib (-3)=2; ie … 2, -1, 1, 0, 1, 1, 2,… etc Guess what symFib is doing Dummy values (2) ©University of Sheffieldcom2010

To trap and process errors employ an explicit exception handling technique based on error types defined using algebraic types data Maybe a = Nothing | Just a deriving (Eq, Ord, Read, Show) The type Maybe a is simply the type a extended by an error value Nothing. Any function g that uses the result of another function may be transformed so it accepts an argument of type Maybe a rather than a. This is where the error handling occurs. We can  transmit the error through g  trap the error within g. Exception handling ©University of Sheffieldcom2010

It lifts the function g :: a -> b to a function mapMaybe g :: Maybe a -> Maybe b mapMaybe :: (a->b) -> Maybe a-> Maybe b mapMaybe g Nothing = Nothing mapMaybe g (Just x) = Just (g x) Example mapMaybe (*3) (my_nth 5[1,2,3]) ⇒ Nothing mapMaybe (*3) (my_nth 2[1,2,3]) ⇒ Just 9 If, however, we lift the function g::a -> b to a function of type Maybe a -> b then we are trapping the error. Transmit (map) an error ©University of Sheffieldcom2010

trapMaybe dummy g :: Maybe a -> b trapMaybe :: b->(a->b) -> Maybe a-> b trapMaybe dummy g Nothing = dummy trapMaybe dummy g (Just x) = g x Error handling. Steps: Error identification (use type Maybe a ) Error mapping (lift g to mapMaybe ) Error trapping (lift g to trapMaybe ) Trap an error ©University of Sheffieldcom2010

Nothing trapMaybe dummyInt (1+)(mapMaybe (*3)(my_nth 5[1,2,3]))  dummyInt integer value trapMaybe dummyInt (1+)(mapMaybe (*3)(my_nth 2[1,2,3]))  10 mapMaybe either sends up Nothing or Maybe value trapMaybe either produces a dummy_value or transforms Maybe value into (1+) value Example ©University of Sheffieldcom2010