Advanced Functional Programming 2009 Ulf Norell (lecture by Jean-Philippe Bernardy)

Slides:



Advertisements
Similar presentations
Functional Programming Lecture 10 - type checking.
Advertisements

CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
Comp 205: Comparative Programming Languages Functional Programming Languages: More Haskell Nested definitions Lists Lecture notes, exercises, etc., can.
ECS 15 if and random. Topic  Testing user input using if statements  Truth and falsehood in Python  Getting random numbers.
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
Recursive Data Types Koen Lindström Claessen. Modelling Arithmetic Expressions Imagine a program to help school-children learn arithmetic, which presents.
Grab Bag of Interesting Stuff. Topics Higher kinded types Files and handles IOError Arrays.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Higher-Order Functions Koen Lindström Claessen. What is a “Higher Order” Function? A function which takes another function as a parameter. Examples map.
Laziness and Infinite Datastructures Koen Lindström Claessen.
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)
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
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.
Tuples and Lists Lecture 3, Programmeringsteknik del A.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
Chapter 9: Functional Programming in a Typed Language.
Overview of the Haskell 98 Programming Language
© M. Winter COSC 4P41 – Functional Programming Programming with actions Why is I/O an issue? I/O is a kind of side-effect. Example: Suppose there.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
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.
Case Study: Route Finding Lecture 6, Programmeringsteknik del A.
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,
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.
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.
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
Functional Programming
Laziness and Infinite Datastructures
Conditional Expressions
Exam #1 You will have exactly 30 Mins to complete the exam.
Koen Lindström Claessen
dr Robert Kowalczyk WMiI UŁ
Theory of Computation Lecture 4: Programs and Computable Functions II
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Higher-Order Functions
PROGRAMMING IN HASKELL
Debugging Haskell by Observing Intermediate Data Structures
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
Main Points of Haskell Functional programming Laziness
PROGRAMMING IN HASKELL
Computer Science 312 Haskell Lists 1.
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
Lazy Programming Lazy evaluation:
CSE 3302 Programming Languages
Theory of Computation Lecture 4: Programs and Computable Functions II
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Review Previously in: Lots of language features: functions, lists, records, tuples, variants, pattern matching Today: No new language features New idioms.
Presentation transcript:

Advanced Functional Programming 2009 Ulf Norell (lecture by Jean-Philippe Bernardy)

This Course Advanced Programming Language Features –Type systems –Programming techniques In the context of Functional Programming –Haskell Applications

Self Study You need to read yourself Find out information yourself Solve problems yourself With a lot of help from us! –All information is on webpage –Discussion board and mailing list

Organization 2 Lectures per week –In the beginning 3 Programming Labs –In pairs 1 Written Exam

Getting Help Course Homepage –Should have all information –Complain if not! Discussion Board –Everyone should become a member –Discuss general topics Mailing List (goes to teachers) –Organizational help –Specific help with programming labs Consulting Hours –Once a week

Recalling Haskell Purely Functional Language –Referential transparency Lazy Programming Language –Things are evaluated at most once Advanced Type System –Polymorphism –Type classes –...

Functions vs. Instructions f :: String -> Int g :: String -> IO Int vs Compare: Only the knowledge about the string is needed to understand the result… Anything can be used to compute the result: Reading from files, randomness, user input…! Moreover, anything can be modified or changed!

Programming with IO hello :: IO () hello = do putStrLn ”Hello! What is your name?” name <- getLine putStrLn (”Hi, ” ++ name ++ ”!”)

Programming with IO printTable :: [String] -> IO () printTable xs = prnt 1 xs where prnt i [] = return () prnt i (x:xs) = do putStrLn (show i ++ ”:” ++ x) prnt (i+1) xs printTable :: [String] -> IO () printTable xs = sequence_ [ putStrLn (show i ++ ":" ++ x) | (x,i) <- xs `zip` [1..length xs] ] sequence_ :: [IO a] -> IO () IO actions are first class.

A Function fun :: Maybe Int -> Int fun mx | mx == Nothing = 0 | otherwise = x + 3 where x = fromJust mx Could fail… What happens?

Another Function expn :: Integer -> Integer expn n | n <= 1 = 1 | otherwise = expn (n-1) + expn (n-2) Main> choice False 17 (expn 99) 17 choice :: Bool -> a -> a -> a choice False x y = x choice True x y = y Without delay…

Laziness Haskell is a lazy language –Things are evaluated at most once –Things are only evaluated when they are needed –Things are never evaluated twice

Understanding Laziness Use error or undefined to see whether something is evaluated or not –choice False 17 undefined –head [3,undefined,17] –head (3:4:undefined) –head [undefined,17,13] –head undefined

Lazy Programming Style Separate –Where the computation of a value is defined –Where the computation of a value happens Modularity!

When is a Value ”Needed”? strange :: Bool -> Integer strange False = 17 strange True = 17 Main> strange undefined Program error: undefined An argument is evaluated when a pattern match occurs But also primitive functions evaluate their arguments

At Most Once? foo :: Integer -> Integer foo x = f x + f x bar :: Integer -> Integer -> Integer bar x y = f 17 + x + y Main> bar bar f 17 is evaluated twice f x is evaluated twice Quiz: How to avoid recomputation?

At Most Once! foo :: Integer -> Integer foo x = fx + fx where fx = f x bar :: Integer -> Integer -> Integer bar x y = f17 + x + y f17 :: Integer f17 = f 17

Infinite Lists Because of laziness, values in Haskell can be infinite Do not compute them completely! Instead, only use parts of them

Examples Uses of infinite lists –take n [3..] –xs `zip` [1..]

Example: PrintTable printTable :: [String] -> IO () printTable xs = sequence_ [ putStrLn (show i ++ ":" ++ x) | (x,i) <- xs `zip` [1..] ] lengths adapt to each other

Iterate iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) Main> iterate (*2) 1 [1,2,4,8,16,32,64,128,256,512,1024,...

Other Handy Functions repeat :: a -> [a] repeat x = x : repeat x cycle :: [a] -> [a] cycle xs = xs ++ cycle xs Quiz: How to define repeat with iterate?

Alternative Definitions repeat :: a -> [a] repeat x = iterate id x cycle :: [a] -> [a] cycle xs = concat (repeat xs)

Problem: Replicate replicate :: Int -> a -> [a] replicate = ? Main> replicate 5 ’a’ ”aaaaa”

Problem: Replicate replicate :: Int -> a -> [a] replicate n x = take n (repeat x)

Problem: Grouping List Elements group :: Int -> [a] -> [[a]] group = ? Main> group 3 ”apabepacepa!” [”apa”,”bep”,”ace”,”pa!”]

Problem: Grouping List Elements group :: Int -> [a] -> [[a]] group n = takeWhile (not. null). map (take n). iterate (drop n). connects ”stages” --- like Unix pipe symbol |

Problem: Prime Numbers primes :: [Integer] primes = ? Main> take 4 primes [2,3,5,7]

Problem: Prime Numbers primes :: [Integer] primes = sieve [2..] where sieve (x:xs) = x : sieve [ y | y <- xs, y `mod` x /= 0 ] Commonly mistaken for Eratosthenes' sieve 1 1 Melissa E. O’Neill, The Genuine Sieve of Eratosthenes. JFP 2008.

Infinite Datastructures data Labyrinth = Crossroad { what :: String, left :: Labyrinth, right :: Labyrinth } How to make an interesting labyrinth?

Infinite Datastructures labyrinth :: Labyrinth labyrinth = start where start = Crossroad ”start” forest town town = Crossroad ”town” start forest forest = Crossroad ”forest” town exit exit = Crossroad ”exit” exit exit What happens when we print this structure?

Laziness Conclusion Laziness –Evaluated at most once –Programming style Do not have to use it –But powerful tool! Can make programs more ”modular”

Type Classes class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool class Eq a => Ord a where ( a -> Bool (>=) :: a -> a -> Bool

Type Classes class Finite a where domain :: [a] What types could be an instance of this class? Can you make functions instance of Eq now?

Focus of This Course Libraries –Solve a problem –in a problem domain Programming Languages –General purpose –Domain-specific –Description languages E.g. JavaScript E.g. HTML, PostScript Little languages

Focus of This Course Two Ideas –Implement little language as library –View libraries as little languages Embedded Language –A little language implemented as a library

Typical Embedded Language Modelling elements in problem domain Functions for creating elements –Constructor functions Functions for modifying or combining –Combinators Functions for observing elements –Run functions

Example: An embedded language for time varying values