0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
Chapter 11 Proof by Induction. Induction and Recursion Two sides of the same coin.  Induction usually starts with small things, and then generalizes.
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
Induction and recursion
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Chapter 9 More About Higher-Order Functions. Currying Recall the function: simple n a b = n * (a+b) Note that: simple n a b is really (((simple n) a)
Higher-Order Functions Koen Lindström Claessen. What is a “Higher Order” Function? A function which takes another function as a parameter. Examples map.
A Lightning Tour of Haskell Lecture 1, Designing and Using Combinators John Hughes.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 20: Lists and Higher-Order Functions in Haskell COMP 144 Programming Language Concepts.
Advanced Programming Handout 4. Introductions  Me: Benjamin C. Pierce (known as Benjamin, or, if you prefer, Dr. Pierce, but not Ben or Professor) 
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions.
Advanced Programming Handout 7 More About Higher-Order Functions (SOE Chapter 9)
Comp 205: Comparative Programming Languages Lazy Evaluation Errors Evaluation Strategies Infinite Lists…. Lecture notes, exercises, etc., can be found.
Chapter 5 Polymorphic and Higher-Order Functions.
Comp 205: Comparative Programming Languages Functional Programming Languages: More Lists Recursive definitions List comprehensions Lecture notes, exercises,
Programovací jazyky F# a OCaml Chapter 5. Hiding recursion using function-as-values.
Induction and recursion
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
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.
What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values: True.
COMP313A Functional Programming (1)
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.
Functional Programming Lecture 3 - Lists Muffy Calder.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
1 Proving Properties of Recursive List Functions CS 270 Math Foundations of CS Jeremy Johnson.
© 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.
Chapter 5 1. Chapter Summary  Mathematical Induction  Strong Induction  Recursive Definitions  Structural Induction  Recursive Algorithms.
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}
Conditional Expressions
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
Induction and recursion
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Higher Order Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CS 457/557: Functional Languages Folds
CSE 3302 Programming Languages
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Presentation transcript:

0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions

1 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 f x = f (f x) twice is higher-order because it takes a function (f) as its first argument.

2 Why Are They Useful? zCommon programming idioms can be encoded as functions within the language itself. zDomain specific languages can be defined as collections of higher-order functions. zAlgebraic properties of higher-order functions can be used to reason about programs.

3 The Map Function The higher-order library function called map applies a function to every element of a list. map :: (a  b)  [a]  [b] For example: > map (+1) [1,3,5,7] [2,4,6,8] Try it. Hugs> map (+1) [1,3,5,7] [2,4,6,8]

4 Alternatively, for the purposes of proofs, the map function can also be defined using recursion: The map function can be defined in a particularly simple manner using a list comprehension: map f xs = [f x | x  xs] map f [] = [] map f (x:xs) = f x : map f xs Understand?

5 The Filter Function The higher-order library function filter selects every element from a list that satisfies a predicate. filter :: (a  Bool)  [a]  [a] For example: > filter even [1..10] [2,4,6,8,10] Try it. Hugs> filter even [1..10] [2,4,6,8,10]

6 Alternatively, it can be defined using recursion: Filter can be defined using a list comprehension: filter p xs = [x | x  xs, p x] filter p [] = [] filter p (x:xs) | p x = x : filter p xs | otherwise = filter p xs

7 The Foldr Function A number of functions on lists can be defined using the following simple pattern of recursion: f [] = v 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. Examples to follow.

8 For example: sum [] = 0 sum (x:xs) = x + sum xs and [] = True and (x:xs) = x && and xs product [] = 1 product (x:xs) = x * product xs v = 0  = + v = 1  = * v = True  = && These all follow the format on the previous page.

9 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

10 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.

11 Foldr as substitution and evaluation Think of the list [a, b, c] as a data structure. : / \ a : / \ b : / \ c [] f / \ a f / \ b f / \ c v zIn effect, we have converted a list data structure [a, b, c] into an expression that can be evaluated. zIf f is (+) and v is 0, we have defined sum using foldr by converting the original list into this expression. + / \ a + / \ b + / \ c 0 When evaluated, we will get the sum of the list [a, b, c]. zReplace ''[] ''with'' v''. zAt each (:) node build an expression to perform the ''f'' computation on the two subtrees. yThe left subtree will be an element from the original list. yThe right subtree will be the result of having performed the computation on the rest of the list.

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

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

14 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

15 length [1,2,3] length (1:(2:(3:[]))) = 1+(1+(1+0)) = 3 = Hence, we have: length = foldr ( _ n  1+n) 0 Replace each (:) by _ n  1+n and [] by 0. For example: g / \ a g / \ b g / \ c 0 g = _ n  1+n Understand?

16 Now recall the reverse function: reverse [] = [] reverse (x:xs) = reverse xs ++ [x] reverse [1,2,3] reverse (1:(2:(3:[]))) = (([] ++ [3]) ++ [2]) ++ [1] = [3,2,1] = For example: Replace each (:) by x xs  xs ++ [x] and [] by []. Hence, we have: reverse = foldr ( x xs  xs ++ [x]) [] Note xs and [x] are reversed.

17 Finally, we note that the append function ( ++ ) has a particularly compact definition using foldr: (++ ys) = foldr (:) ys Replace each (:) by (:) and [] by ys. This defines (++) as a function g. Hugs> g [1, 2, 3] [4, 5, 6] where g xs ys = (foldr (:) ys) xs [1,2,3,4,5,6] This is a “section.” The first argument (the xs) is not shown.

18 ++ [1, 2, 3] [4, 5, 6] (foldr (:) [4, 5, 6]) [1, 2, 3] (++ ys) = foldr (:) ys : / \ 1 : / \ 2 : / \ 3 [4, 5, 6] 1 : 2 : 3 : [4, 5, 6] In other words: xs ++ ys = (foldr (:) ys) xs This is a “section.” (++) xs ys = (foldr (:) ys) xs = = =

19 Why Is Foldr Useful? zSome recursive functions on lists, such as sum, are simpler to define using foldr. zProperties of functions defined using foldr can be proved using algebraic properties of foldr, such as fusion and the banana split rule. zAdvanced program optimisations can be simpler if foldr is used in place of explicit recursion.

20 Other (Higher Order) 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

21 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

22 Dually, 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

23 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"

24 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"

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