First Class Mapping Folding functions
Map and Foldr
- Dr. Mattox Beckman
Map and Foldr Dr. Mattox Beckman University of Illinois at - - PowerPoint PPT Presentation
First Class Mapping Folding functions Map and Foldr Dr. Mattox Beckman University of Illinois at Urbana-Champaign Department of Computer Science First Class Mapping Folding functions Objectives Explain the concept of fjrst class
First Class Mapping Folding functions
First Class Mapping Folding functions
First Class Mapping Folding functions
First Class Mapping Folding functions
1 sqr a = a * a 2 hypotsq a b = sqr a + sqr b
1 sqr :: Integer -> Integer 2 sqr :: Num a => a -> a 3 hypotsq :: Num a => a -> a -> a 4 Prelude> sqr 10 5 100 6 Prelude> hypotsq 3 4 7 25
First Class Mapping Folding functions
1 inc x = x + 1 2 double x = x * 2 3 compose f g x = f (g x)
1 compose :: (t1 -> t2) -> (t -> t1) -> t -> t2 2 Prelude> :t double 3 double :: Integer -> Integer 4 Prelude> double 10 5 20 6 Prelude> compose inc double 10 7 21
First Class Mapping Folding functions
1 twice f x = f (f x)
First Class Mapping Folding functions
1 \x -> x + 1
◮ Backslash (a.k.a. lambda) ◮ Parameter list ◮ Arrow ◮ Body of function 1 prelude> (\x -> x + 1) 41 2 42
First Class Mapping Folding functions
1 inc :: (Num t) => t -> t 2 inc a = a + 1 3 inc = \a -> a + 1 4 5 plus :: (Num t) => t -> t -> t 6 plus a b = a + b 7 plus = \a -> \b -> a + b
First Class Mapping Folding functions
1 inc :: (Num t) => t -> t 2 inc a = a + 1 3 inc = \a -> a + 1 4 5 plus :: (Num t) => t -> t -> t 6 plus a b = a + b 7 plus = \a -> \b -> a + b
1 inc = plus 1
First Class Mapping Folding functions
1 plus a b = (+) a b 2 plus a = (+) a 3 plus = (+)
1 inc x = x + 1 2 inc = (+) 1 3 inc = (+1)
First Class Mapping Folding functions
1 incL [] = [] 2 incL (x:xs) = x+1 : incL xs
First Class Mapping Folding functions
1 incL [] = [] 2 incL (x:xs) = x+1 : incL xs
1 doubleL [] = [] 2 doubleL (x:xs) = x*2 : doubleL xs
First Class Mapping Folding functions
1 incL [] = [] ← Base Case 2 incL (x:xs) = x+1 : incL xs
1 doubleL [] = [] ← Base Case 2 doubleL (x:xs) = x*2 : doubleL xs
◮ The operations we perform ◮ The names of the functions
First Class Mapping Folding functions
First Class Mapping Folding functions
1 map :: (a->b) -> [a] -> [b] 2 map f [] = [] 3 map f (x:xs) = f x : map f xs 4 5 incL = map inc 6 7 doubleL = map double
First Class Mapping Folding functions
1 sumL [] = 0 2 sumL (x:xs) = x + sumL xs
1 prodL [] = 1 2 prodL (x:xs) = x * prodL xs
First Class Mapping Folding functions
1 foldr :: (a -> b -> b) -> b -> [a] -> [b] 2 foldr f z [] = z 3 foldr f z (x:xs) = f x (foldr f z xs) 4 5 sumlist = foldr (+) 0 6 prodlist = foldr (*) 1
First Class Mapping Folding functions
1 plus a b = a + b 2 sum [] = 0 3 sum (x:xs) = plus x (sum xs)
1 sum = foldr (\a b -> plus a b) 0
First Class Mapping Folding functions