Quiz Introducing Higher-Order Functions Contents of the Kahoot quiz at the begining of Lecture 4B 2018 Dave Sands This is a literate Haskell file. All code is explicitly marked with a ">". Everything else is a comment. It loads in ghci just like any other haskell file. Try to answer the questions then try them out to see what is the right answer. ----------------------------------------------------- Q1 The function map works like this: > prop_map1 = map even [2,3,4] == [True,False,True] > prop_map2 = map abs [-1,0] == [1,0] > prop_map3 = map abs [] == [] What does example1 give? > example1 = map up [1,2,3] > where up n = n + 2 > a1 = [2,3,4] > a2 = [3,4,5] > a3 = [1,2,3] > a4 = undefined -- it gives an error ----------------------------------------------------- Q2 What value does p give? > p = sum (map abs [2,-2,3]) Which of these properties is true for map? (there are four possible answers!) > prop_map4 f xs = length (map f xs) == length xs > prop_map5 f x xs = map f (x:xs) == f x : map f xs ----------------------------------------------------- Q3 Exactly one of these definitions for map is NOT correct: > map1 f [] = [] > map1 f (x:xs) = f x : map1 f xs > map2 f xs = [f x | x <- xs] > map3 f xs = [f x | x <- map3 f xs] Which one? ----------------------------------------------------- Q4 map is called a higher-order function because one of its arguments is a function Which of these are higher-order functions? > h1 x y = x (y ++ "\n") > h2 x y = map x y > h3 x y = even x && odd y To find the answer look at the types for each of these. Look for a type where one of the arguments is a function (i.e. it has a -> in its type) ----------------------------------------------------- Q5 The definition of map: map f xs = [f x | x <- xs] -- So the type of map is map :: [t] -> [u] map :: u -> [t] -> [u] map :: (t -> u) -> [t] -> [u] Simply type :t map at the ghci prompt for the answer ---------------------------------------------------- ------------------------------------------------------ Q6 Standard function filter can be defined filter p xs = [ x | x <- xs, p x] -- Some examples of the function filter > prop_filter1 = filter odd [1,2,3,4,5] == [1,3,5] > prop_filter2 = filter even [1,2,3,4,5] == [2,4] What does filter abs [1,-1,0] give? ---------------------------------------------------- Q7 filter p xs = [x | x <- xs, p x] > ex = filter even [1..10] ex gives the value: > a1 = [1,3,5,7,9] > a2 = [2,4,6,8,10] > a3 = False or does it give something else? ------------------------------------------------------- Q8 Combining map and filter map operates on every element in a list filter selects some elements from a list > example = map even (filter odd [1..3]) -- example is equal to which of these? > a1 = [1,3] > a2 = [True,False,True] > a3 = [False,False] > a4 = [True,True]