Higher Order Functions

Slides:



Advertisements
Similar presentations
Lecture 9 Polymorphism, Overloading and Higher Order Functions 1 Polymorphism and Overloading.
Advertisements

Introduction A function is called higher-order if it takes a function as an argument or returns a function as a result. twice :: (a  a)  a  a twice.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
F28PL1 Programming Languages Lecture 14: Standard ML 4.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
Cs776(Prasad)L7fold1 Fold Operations Abstracting Repetitions.
Chapter 11 Proof by Induction. Induction and Recursion Two sides of the same coin.  Induction usually starts with small things, and then generalizes.
Comp 205: Comparative Programming Languages Higher-Order Functions Functions of functions Higher-order functions on lists Reuse Lecture notes, exercises,
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
© M. Winter COSC 4P41 – Functional Programming Patterns of computation over lists Applying to all – mapping map :: (a -> b) -> [a] -> [b] map f.
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
Higher-Order Functions Koen Lindström Claessen. What is a “Higher Order” Function? A function which takes another function as a parameter. Examples map.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions.
Comp 205: Comparative Programming Languages Lazy Evaluation Errors Evaluation Strategies Infinite Lists…. Lecture notes, exercises, etc., can be found.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
0 PROGRAMMING IN HASKELL Chapter 9 - Higher-Order Functions, Functional Parsers.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Recursion on Lists Lecture 5, Programmeringsteknik del A.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
Recursion Higher Order Functions CSCE 314 Spring 2016.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
Computer Eng. Software Lab II , Semester 2, Who I am: Andrew Davison CoE, WiG Lab Office Functional Programming.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
CSE 3302 Programming Languages Chengkai Li Spring 2008 Functional Programming Language: Haskell (cont’d) Lecture 20 – Functional Programming, Spring 2008.
© M. Winter COSC 4P41 – Functional Programming Some functions id :: a -> a id x = x const :: a -> b -> a const k _ = k ($) :: (a -> b) -> a -> b.
Lecture 14: Advanced Topic: Functional Programming
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Polymorphic Functions
Functional Programming
CS314 – Section 5 Recitation 10
Conditional Expressions
Recursion.
Types CSCE 314 Spring 2016.
Functional Programming Lecture 12 - more higher order functions
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Higher-Order Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CMSC 330: Organization of Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Higher Order Functions
Abstracting Repetitions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CS 457/557: Functional Languages Folds
CSE-321 Programming Languages Introduction to Functional Programming
HIGHER ORDER FUNCTIONS
CSE 3302 Programming Languages
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
Higher-Order Functions in Haskell
PROGRAMMING IN HASKELL
GC16/3011 Functional Programming Lecture 9 Higher Order Functions
Presentation transcript:

Higher Order Functions CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions

Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result. twice is higher-order because it takes a function as its first argument. twice :: (a → a) → a → a twice f x = f (f x) Note: Higher-order functions are very common in Haskell (and in functional programming). Writing higher-order functions is crucial practice for effective programming in Haskell, and for understanding others’ code.

Why Are They Useful? Common programming idioms can be encoded as functions within the language itself. Domain specific languages can be defined as collections of higher- order functions. For example, higher-order functions for processing lists. Algebraic properties of higher-order functions can be used to reason about programs.

The Map Function The higher-order library function called map applies a function to every element of a list. map :: (a → b) → [a] → [b] > map (+1) [1,3,5,7] [2,4,6,8] For example: The map function can be defined in a particularly simple manner using a list comprehension: map f xs = [f x | x ← xs] Alternatively, it can also be defined using recursion: map f [] = [] map f (x:xs) = f x : map f xs

The Filter Function The higher-order library function filter selects every element from a list that satisfies a predicate. filter :: (a → Bool) → [a] → [a] > filter even [1..10] [2,4,6,8,10] For example: Filter can be defined using a list comprehension: filter p xs = [x | x ← xs, p x] Alternatively, it can also be defined using recursion: filter p [] = [] filter p (x:xs) | p x = x : filter p xs | otherwise = filter p xs

The foldr Function A number of functions on lists can be defined using the following simple pattern of recursion: f [] = v0 f (x:xs) = x ⊕ f xs f maps the empty list to some value v, and any non-empty list to some function ⊕ applied to its head and f of its tail.

For example: sum [] = 0 sum (x:xs) = x + sum xs v0 = 0 ⊕ = + product [] = 1 product (x:xs) = x * product xs v0 = 1 ⊕ = * and [] = True and (x:xs) = x && and xs v0 = True ⊕ = &&

The higher-order library function foldr (fold right) encapsulates this simple pattern of recursion, with the function ⊕ and the value v as arguments. For example: sum = foldr (+) 0 product = foldr (*) 1 or = foldr (||) False and = foldr (&&) True

foldr itself can be defined using recursion: foldr :: (a → b → b) → b → [a] → b foldr f v [] = v foldr f v (x:xs) = f x (foldr f v xs) However, it is best to think of foldr non-recursively, as simultaneously replacing each (:) in a list by a given function, and [] by a given value.

For example: sum [1,2,3] foldr (+) 0 [1,2,3] = foldr (+) 0 (1:(2:(3:[]))) = 1+(2+(3+0)) = 6 = Replace each (:) by (+) and [] by 0.

For example: = = = = product [1,2,3] foldr (*) 1 [1,2,3] 1*(2*(3*1)) = 6 = Replace each (:) by (*) and [] by 1.

Other foldr Examples Even though foldr encapsulates a simple pattern of recursion, it can be used to define many more functions than might first be expected. Recall the length function: length :: [a] → Int length [] = 0 length (_:xs) = 1 + length xs

length = foldr (\_ n -> 1+n) 0 For example: length [1,2,3] length (1:(2:(3:[]))) = 1+(1+(1+0)) = Replace each (:) by λ_ n → 1+n and [] by 0 3 = Hence, we have: length = foldr (\_ n -> 1+n) 0

Now the reverse function: reverse (x:xs) = reverse xs ++ [x] For example: Replace each (:) by λx xs → xs ++ [x] and [] by [] reverse [1,2,3] reverse (1:(2:(3:[]))) = (([] ++ [3]) ++ [2]) ++ [1] = [3,2,1] = Hence, we have: reverse = foldr (\x xs -> xs ++ [x]) [] Here, the append function (++) has a particularly compact definition using foldr: Replace each (:) by (:) and [] by ys. (++ ys) = foldr (:) ys

Why Is foldr Useful? Some recursive functions on lists, such as sum, are simpler to define using foldr. Properties of functions defined using foldr can be proved using algebraic properties of foldr. Advanced program optimizations can be simpler if foldr is used in place of explicit recursion.

foldr and foldl foldr :: (a → b → b) → b → [a] → b foldr f v [] = v foldr f v (x:xs) = f x (foldr f v xs) foldl :: (a → b → a) → a → [b] → a foldl f v [] = v foldl f v (x:xs) = foldl f (f v x) xs foldr 1 : 2 : 3 : [] => (1 + (2 + (3 + 0))) foldl 1 : 2 : 3 : [] => (((0 + 1) + 2) + 3)

Other Library Functions The library function (.) returns the composition of two functions as a single function. (.) :: (b -> c) -> (a -> b) -> (a -> c) f . g = \x -> f (g x) For example: odd :: Int → Bool odd = not . even Exercise: Define filterOut p xs that retains elements that do not satisfy p. filterOut p xs = filter (not . p) xs > filterOut odd [1..10] [2,4,6,8,10]

The library function all decides if every element of a list satisfies a given predicate. all :: (a → Bool) → [a] → Bool all p xs = and [p x | x ← xs] For example: > all even [2,4,6,8,10] True

Conversely the library function any decides if at least one element of a list satisfies a predicate. any :: (a → Bool) → [a] → Bool any p xs = or [p x | x ← xs] For example: > any isSpace "abc def" True

The library function takeWhile selects elements from a list while a predicate holds of all the elements. takeWhile :: (a → Bool) → [a] → [a] takeWhile p [] = [] takeWhile p (x:xs) | p x = x : takeWhile p xs | otherwise = [] For example: > takeWhile isAlpha "abc def" "abc"

Dually, the function dropWhile removes elements while a predicate holds of all the elements. dropWhile :: (a → Bool) → [a] → [a] dropWhile p [] = [] dropWhile p (x:xs) | p x = dropWhile p xs | otherwise = x:xs For example: > dropWhile isSpace " abc" "abc"

filter, map and foldr Typical use is to select certain elements, and then perform a mapping, for example, sumSquaresOfPos ls = foldr (+) 0 (map (^2) (filter (>= 0) ls)) > sumSquaresOfPos [-4,1,3,-8,10] 110 In pieces: keepPos = filter (>= 0) mapSquare = map (^2) sum = foldr (+) 0 sumSquaresOfPos ls = sum (mapSquare (keepPos ls)) Alternative definition: sumSquaresOfPos = sum . mapSquare . keepPos

Exercises (1) What are higher-order functions that return functions as results better known as? (2) Express the comprehension [f x | x ← xs, p x] using the functions map and filter. (3) Redefine map f and filter p using foldr.