Chapter 5 Polymorphic and Higher-Order Functions.

Slides:



Advertisements
Similar presentations
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Advertisements

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.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
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,
String is a synonym for the type [Char].
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
Cse536 Functional Programming 1 6/10/2015 Lecture #6, Oct 13, 2004 Reading Assignments –Read chapter 5 of the Text Polymorphic and Higher-Order Functions.
Cse536 Functional Programming 1 6/10/2015 Lecture #8, Oct. 20, 2004 Todays Topics –Sets and characteristic functions –Regions –Is a point in a Region –Currying.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Chapter 3 Simple Graphics. Side Effects and Haskell  All the programs we have seen so far have no “side-effects.” That is, programs are executed only.
Cse536 Functional Programming 1 6/11/2015 Lecture #5, Oct 11, 2004 Reading Assignments –Finish Chapter 3, Simple Graphics –Read Chapter 4, Shapes II, Drawing.
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
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)
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.
Chapter 4 Shapes II: Drawing Shapes. Recall the Shape Datatype data Shape = Rectangle Side Side | Ellipse Radius Radius | RtTriangle Side Side | Polygon.
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
Advanced Programming Handout 4. Introductions  Me: Benjamin C. Pierce (known as Benjamin, or, if you prefer, Dr. Pierce, but not Ben or Professor) 
Advanced Programming Handout 12 Higher-Order Types (SOE Chapter 18)
Cse536 Functional Programming 1 6/23/2015 Lecture #17, Dec. 1, 2004 Todays Topics – Higher Order types »Type constructors that take types as arguments.
Chapter 1 Problem Solving, Programming, and Calculation.
Advanced Programming Andrew Black and Tim Sheard Lecture 4 Intro to Haskell.
Advanced Programming Handout 7 More About Higher-Order Functions (SOE Chapter 9)
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.
Tuples and Lists Lecture 3, Programmeringsteknik del A.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
0 PROGRAMMING IN HASKELL Chapter 9 - Higher-Order Functions, Functional Parsers.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
CS5205Haskell1 CS5205: Foundations in Programming Languages FP with Haskell A pure lazy functional language that embodies many innovative ideas in language.
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.
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 Haskell Kevin Atkinson John Simmons. 2 Contents Introduction Type System Variables Functions Module System I/O Conclusions.
Com Functional Programming Lazy Evaluation Marian Gheorghe Lecture 13 Module homepage Mole & ©University of Sheffieldcom2010.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
Recursion on Lists Lecture 5, Programmeringsteknik del A.
Grab Bag of Interesting Stuff. Higher Order types Type constructors are higher order since they take types as input and return types as output. Some type.
CS5205Haskell1 CS5205: Foundation in Programming Languages Basics of Functional Programming.
Chapter SevenModern Programming Languages1 A Second Look At ML.
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,
More Data Types CSCE 314 Spring CSCE 314 – Programming Studio Defining New Data Types Three ways to define types: 1.type – Define a synonym for.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
© 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.
String is a synonym for the type [Char].
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
Functional Programming Lecture 12 - more higher order functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Higher Order Functions
CS 457/557: Functional Languages Folds
CSE-321 Programming Languages Introduction to Functional Programming
Announcements Quiz 5 HW6 due October 23
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Presentation transcript:

Chapter 5 Polymorphic and Higher-Order Functions

Polymorphic Length length :: [a] -> Int length [] = 0 length (x:xs) = 1 + length xs Polymorphic functions don’t “look at” their polymorphic arguments, and thus don’t care what the type is: length [1,2,3]  3 length [’a’,’b’,’c’]  3 length [[2],[],[1,2,3]]  3 “ a ” is a type variable. It is lowercase to distinguish it from type names, which are capitalized.

Polymorphism  Many predefined functions are polymorphic. For example: (++) :: [a] -> [a] -> [a] id :: a -> a head :: [a] -> a tail :: [a] -> [a] [] :: [a] -- interesting!  But you can define your own as well. For example, suppose we define: tag1 x = (1,x) Then: Hugs> :type tag1 tag1 :: a -> (Int,a)

Polymorphic Data Structures  Polymorphism is common in data structures that “don’t care” what kind of data they contain.  The examples on the previous page involve lists and tuples. In particular, note that: (:) :: a -> [a] -> [a] (,) :: a -> b -> (a,b) (note the way that the tupling operator is identified – which generalizes to (,,), (,,,), etc.)  But we can also easily define new data structures that are polymorphic.

Example  The type variable a causes Maybe to be polymorphic: data Maybe a = Nothing | Just a  Note the types of the constructors: Nothing :: Maybe a Just :: a -> Maybe a  Thus: Just 3 :: Maybe Int Just “x“ :: Maybe String Just (3,True) :: Maybe (Int,Bool) Just (Just 1) :: Maybe (Maybe Int)

Maybe may be useful  The most common use of Maybe is with a function that “may” return a useful value, but may also fail.  For example, the division operator (/) in Haskell will cause a run-time error if its second argument is zero. Thus we may wish to define a “safe” division function, as follows: safeDivide :: Int -> Int -> Maybe Int safeDivide x 0 = Nothing safeDivide x y = Just (x/y)

Abstraction Over Recursive Definitions  Recall from Section 4.1: transList [] = [] transList (p:ps) = trans p : transList ps putCharList [] = [] putCharList (c:cs) = putChar c : putCharList cs  There is something strongly similar about these definitions. Indeed, the only thing different about them (besides the variable names) is the function trans vs. the function putChar.  We can use the abstraction principle to take advantage of this.

Abstraction Yields map  trans and putChar are what’s different; so they should be arguments to the abstracted function.  In other words, we would like to define a function called map (say) such that map trans behaves like transList, and map putChar behaves like putCharList.  No problem: map f [] = [] map f (x:xs) = f x : map f xs  Given this, it is not hard to see that we can redefine transList and putCharList as: transList xs = map trans xs putCharList cs = map putChar cs

map is Polymorphic  The greatest thing about map is that it is polymorphic. Its most general (i.e. principal) type is: map :: (a->b) -> [a] -> [b] Note that whatever type is instantiated for “ a ” must be the same at both instances of “ a ”; the same is true for “ b ”.  For example, since trans :: Vertex -> Point, then map trans :: [Vertex] -> [Point] and since putChar :: Char -> IO (), then map putChar :: [Char] -> [IO ()]

Arithmetic Sequences  Special syntax for computing lists with regular properties. [1.. 6] = [1,2,3,4,5,6] [1,3.. 9] = [1,3,5,7,9] [5,4.. 1] = [5,4,3,2,1]  Infinite lists too! take 9 [1,3..] = [1,3,5,7,9,11,13,15,17] take 5 [5..] = [5,6,7,8,9]

Another Example conCircles = map circle [2.4, ] coloredCircles = zip [Black,Blue,Green,Cyan,Red,Magenta,Yellow,White] conCircles main = runGraphics $ do w <- openWindow "Drawing Shapes" (xWin,yWin) drawShapes w (reverse coloredCircles) spaceClose w

The Result

When to Define Higher-Order Functions  Recognizing repeating patterns is the key, as we did for map. As another example, consider: listSum [] = 0 listSum (x:xs) = x + listSum xs listProd [] = 1 listProd (x:xs) = x * listProd xs  Note the similarities. Also note the differences (underlined), which need to become parameters to the abstracted function.

Abstracting  This leads to: fold op init [] = init fold op init (x:xs) = x `op` fold op init xs  Note that fold is also polymorphic: fold :: (a -> b -> b) -> b -> [a] -> b  listSum and listProd can now be redefined: listSum xs = fold (+) 0 xs listProd xs = fold (*) 1 xs

Two Folds are Better than One  fold is predefined in Haskell, though with the name foldr, because it “folds from the right”. That is: foldr op init (x1 : x2 :... : xn : [])  x1 `op` (x2 `op` (...(xn `op` init)...))  But there is another function foldl which “folds from the left”: foldl op init (x1 : x2 :... : xn : [])  (...((init `op` x1) `op` x2)...) `op` xn  Why two folds? Because sometimes using one can be more efficient than the other. For example: foldr (++) [] [x,y,z]  x ++ (y ++ z) foldl (++) [] [x,y,z]  (x ++ y) ++ z The former is more efficient than the latter; but not always – sometimes foldl is more efficient than foldr. Choose wisely!

Reversing a List  Obvious but inefficient (why?): reverse [] = [] reverse (x::xs) = reverse xs ++ [x]  Much better (why?): reverse xs = rev [] xs where rev acc [] = acc rev acc (x:xs) = rev (x:acc) xs  This looks a lot like foldl. Indeed, we can redefine reverse as: reverse xs = foldl revOp [] xs where revOp a b = b : a