Advanced Programming Handout 4. Introductions  Me: Benjamin C. Pierce (known as Benjamin, or, if you prefer, Dr. Pierce, but not Ben or Professor) 

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

Chapter 6 Shapes III: Perimeters of Shapes. The Perimeter of a Shape  To compute the perimeter we need a function with four equations (1 for each Shape.
Chapter 11 Proof by Induction. Induction and Recursion Two sides of the same coin.  Induction usually starts with small things, and then generalizes.
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.
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)
Higher-Order Functions Koen Lindström Claessen. What is a “Higher Order” Function? A function which takes another function as a parameter. Examples map.
Chapter 2 A Module of Shapes: Part I. Defining New Datatypes  The ability to define new data types in a programming language is important.  Kinds of.
Welcome to the CIS Seminar Laziness is good for you!
Cse536 Functional Programming Lecture #14, Nov. 10, 2004 Programming with Streams –Infinite lists v.s. Streams –Normal order evaluation –Recursive streams.
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
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)
Cse536 Functional Programming 1 6/28/2015 Lecture #3, Oct 4, 2004 Reading Assignments –Finish chapter 2 and begin Reading chapter 3 of the Text Today’s.
Chapter 5 Polymorphic and Higher-Order Functions.
Advanced Programming Handout 5 Recursive Data Types (SOE Chapter 7)
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,
Sets.
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.
Functional Programming in Haskell Motivation through Concrete Examples Adapted from Lectures by Simon Thompson.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
Advanced Functional Programming 2009 Ulf Norell (lecture by Jean-Philippe Bernardy)
Modeling with Haskell Scientific Seminar 03/04 Gerhard Navratil.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
© Kenneth C. Louden, Chapter 11 - Functional Programming, Part III: Theory Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee.
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.
Recursion on Lists Lecture 5, Programmeringsteknik del A.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
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,
Recursion Higher Order Functions CSCE 314 Spring 2016.
Haskell Chapter 4. Recursion  Like other languages  Base case  Recursive call  Author programs a number of built-in functions as examples.
Functional Programming Lecture 3 - Lists Muffy Calder.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
CS321 Functional Programming 2 © JAS Programming with Streams A stream is never finite and could be defined as special polymorphic type data stream.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
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.
© 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.
Advanced Functional Programming 2010
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
Recursion.
Types CSCE 314 Spring 2016.
Theory of Computation Lecture 4: Programs and Computable Functions II
Functional Programming Lecture 12 - more higher order functions
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Higher Order Functions
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Higher Order Functions
PROGRAMMING IN HASKELL
CSE 3302 Programming Languages
Announcements Quiz 5 HW6 due October 23
PROGRAMMING IN HASKELL
Theory of Computation Lecture 4: Programs and Computable Functions II
PROGRAMMING IN HASKELL
Presentation transcript:

Advanced Programming Handout 4

Introductions  Me: Benjamin C. Pierce (known as Benjamin, or, if you prefer, Dr. Pierce, but not Ben or Professor)  You?

Any Comments? ... about the class so far, the homework, or anything else? If you think of more comments later, you know where to find me...

Review  What are the types of these functions? f x = [x] g x = [x+1] h [] = 0 h (y:ys) = h ys + 1

Review  How about these? f1 x y = [x] : [y] f2 x [] = x f2 x (y:ys) = f2 y ys f3 [] ys = ys f3 xs [] = xs f3 (x:xs) (y:ys) = f3 ys xs

Review  How about these? foo x y = x (x (x y)) bar x y z = x (y z) baz x (x1:x2:xs) = (x1 `x` x2) : baz xs baz x _ = [] What does baz do?

Review  Recall that map is defined as: map :: (a->b) -> [a] -> [b] map f [] = [] map f (x:xs) = f x : map f xs  What does this function do? mystery f l = map (map f) l

Review  Challenge 2: Use foldr to define map  Recall that foldr is defined as: foldr :: (a->b->b) -> b -> [a] -> b foldr op init [] = init foldr op init (x:xs) = x `op` foldr op init xs  Challenge: Use foldr to define a function maxList :: [Integer] -> Integer that returns the maximum element from its argument. N.b.: This was part of HW 2

Review  Recall that the function zip :: [a] -> [b] -> [(a,b)] takes a pair of lists and returns a list of pairs of their corresponding elements: zip [1,2,3] [True,True,False]  [(1,True), (2,True), (3,False)]  What is its definition?

 The function zipWith :: (a->b->c) -> [a] -> [b] -> [c] generalizes zip : zipWith (+) [1,2,3] [4,5,6]  [5,7,9]  What is its definition? Review  Can zip be defined in terms of zipWith ?  Can zip be defined in terms of foldr or foldl ?

A Quick Footnote (We’re all in this together...)

Clarification  Handout 3 said : “When we write (1,2,3,4) we really mean (1,(2,(3,4))).”  This is “morally true” but misleading: tuple types in Haskell are n-ary, so (Integer,Integer,Integer,Integer) and (Integer,(Integer,(Integer,Integer))) are distinct types and expressions like (1,2,3,4)==(1,(2,(3,4))) are not legal.

A Taste of Infinity

Infinite Lists  Lists in Haskell need not be finite. E.g.: list1 = [1..] -- [1,2,3,4,5,6,...] f x = x : (f (x+1)) list2 = f 1 -- [1,2,3,4,5,6,...] list3 = 1:2:list3 -- [1,2,1,2,1,2,...]

Working with Infinite Lists  O f course, if we try to perform an operation that requires consuming all of an infinite list (such as printing it or finding its length), our program will loop.  However, a program that only consumes a finite part of an infinite list will work just fine. take 5 [10..]  [10,11,12,13,14]

Lazy Evaluation  The feature of Haskell that makes this possible is lazy evaluation.  Only the portion of a list that is actually needed by other parts of the program will actually be constructed at run time.  We will discuss the mechanics of lazy evaluation in much more detail later in the course. Today, let’s look at a real-life example of its use...

Shapes III: Perimeters of Shapes (Chapter 6)

 To compute the perimeter we need a function with four equations (1 for each Shape constructor).  The first three are easy … perimeter :: Shape -> Float perimeter (Rectangle s1 s2) = 2*(s1+s2) perimeter (RtTriangle s1 s2) = s1 + s2 + sqrt (s1^2+s2^2) perimeter (Polygon pts) = foldl (+) 0 (sides pts) -- or: sumList (sides pts)  This assumes that we can compute the lengths of the sides of a polygon. This shouldn’t be too difficult since we can compute the distance between two points with distBetween. The Perimeter of a Shape s1 s2 s1 s2

Recursive Def’n of Sides sides :: [Vertex] -> [Side] sides [] = [] sides (v:vs) = aux v vs where aux v1 (v2:vs’) = distBetween v1 v2 : aux v2 vs’ aux vn [] = distBetween vn v : [] -- i.e. aux vn [] = [distBetween vn v]  But can we do better? Can we remove the direct recursion, as a seasoned functional programmer might?

Visualize What’s Happening  The list of vertices is: vs = [A,B,C,D,E]  We need to compute the distances between the pairs of points (A,B), (B,C), (C,D), (D,E), and (E,A).  Can we compute these pairs as a list? [(A,B),(B,C),(C,D),(D,E),(E,A)]  Yes, by “zipping” the two lists: [A,B,C,D,E] and [B,C,D,E,A] as follows: zip vs (tail vs ++ [head vs]) A B C DE

New Version of sides This leads to: sides :: [Vertex] -> [Side] sides vs = zipWith distBetween vs (tail vs ++ [head vs])

There is one remaining case: the ellipse. The perimeter of an ellipse is given by the summation of an infinite series. For an ellipse with radii r 1 and r 2 : p = 2  r 1 (1 -  s i ) where s 1 = 1/4 e 2 s i = s i-1 (2i-1)(2i-3) e 2 for i > 1 4i 2 e = sqrt (r 1 2 – r 2 2 ) / r 1 Given s i, it is easy to compute s i+1. Perimeter of an Ellipse n.b.: not >= as in handout

Computing the Series nextEl:: Float -> Float -> Float -> Float nextEl e s i = s*(2*i-1)*(2*i-3)*(e^2) / (4*i^2) Now we want to compute [s 1,s 2,s 3, …]. To fix e, let’s define: aux s i = nextEl e s i So, we would like to compute: [s 1, s 2 = aux s 1 2, s 3 = aux s 2 3 = aux (aux s 1 2) 3, s 4 = aux s 3 4 = aux (aux (aux s 1 2) 3) 4,... ] s i+1 = s i (2i-1)(2i-3) e 2 4i 2 Can we capture this pattern?

Scanl (scan from the left)  Yes, using the predefined function scanl: scanl :: (a -> b -> b) -> b -> [a] -> [b] scanl f seed [] = seed : [] scanl f seed (x:xs) = seed : scanl f newseed xs where newseed = f x seed  For example: scanl (+) 0 [1,2,3]  [ 0, 1 = (+) 0 1, 3 = (+) 1 2, 6 = (+) 3 3 ]  [ 0, 1, 3, 6 ]  Using scanl, the result we want is: scanl aux s1 [2..]

r2 = 1.5 r1 = 2.1 [s1 = , s2 = , s3 = , s4 = , s5 = ,...] Note how quickly the values in the series get smaller... Sample Series Values

Putting it all Together perimeter (Ellipse r1 r2) | r1 > r2 = ellipsePerim r1 r2 | otherwise = ellipsePerim r2 r1 where ellipsePerim r1 r2 = let e = sqrt (r1^2 - r2^2) / r1 s = scanl aux (0.25*e^2) (map intToFloat [2..]) aux s i = nextEl e s i test x = x > epsilon sSum = foldl (+) 0 (takeWhile test s) in 2*r1*pi*(1 - sSum) note use of “pattern guards”