Advanced Functional Programming 2010

Slides:



Advertisements
Similar presentations
Comp 205: Comparative Programming Languages Functional Programming Languages: More Haskell Nested definitions Lists Lecture notes, exercises, etc., can.
Advertisements

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.
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.
A Lightning Tour of Haskell Lecture 1, Designing and Using Combinators John Hughes.
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
Advanced Programming Handout 12 Higher-Order Types (SOE Chapter 18)
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 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
Advanced Functional Programming 2009 Ulf Norell (lecture by Jean-Philippe Bernardy)
© 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.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
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.
Två saker ● Labsal bokning ● Sprid ut er över salarna ● “Bracket Matching” [ " Slides: " ++ concat (intersperse ", " (map lnk gs)) | let gs = [ f | f.
CS314 – Section 5 Recitation 9
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
Functional Programming
Laziness and Infinite Datastructures
Conditional Expressions
Recursion.
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
AFP - Lecture 2 Domain Specific Embedded Languages
PROGRAMMING IN HASKELL
Higher-Order Functions
PROGRAMMING IN HASKELL
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
Lecture 2 Domain Specific Embedded Languages
Main Points of Haskell Functional programming Laziness
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Computer Science 312 Haskell Lists 1.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Types and Classes 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
Grab Bag of Interesting Stuff
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 2010 Patrik Jansson (slides by Norell & Bernardy) 1

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

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 Office hours Fri 10-12 3

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

Getting Help Course Homepage Discussion Board 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, Fri 10-12 5

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

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

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

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 IO actions are first class. printTable :: [String] -> IO () printTable xs = sequence_ [ putStrLn (show i ++ ":" ++ x) | (x,i) <- xs `zip` [1..length xs] ] sequence_ :: [IO a] -> IO () 9

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

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

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 12

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 13

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

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

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

At Most Once! So... bindings are evaluated 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 ... in their scope. So, top level ones are really evaluated at most once! 17

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

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

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

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,... 21

Quiz: How to define repeat with iterate? 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? 22

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

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

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

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

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 | 27

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

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

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

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? 31

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

Type Classes class Eq a where (==) :: a -> a -> Bool class Eq a => Ord a where (<=) :: a -> a -> Bool (>=) :: a -> a -> Bool instance Eq Int where ... instance Eq a => Eq [a] where ... sort :: Ord a => [a] -> [a] 33

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? 34

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

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

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 37

Example: An embedded language for time varying values 38