function definitions Flashcards
Give the polymorphic type for each of the following functions:
(a) the identity function [2]
(a) id :: a -> a
(b) the map function [2]
(b) map :: (a -> b) -> [a] -> [b]
(c) the zip function [2]
(c) zip :: [a] -> [b] -> [(a,b)]
(d) the foldr function [2]
(d) foldr :: Foldable t => (a -> b -> b) -> b -> t a ->b
(e) the monad bind function, i.e. (»=)
(e) (»=) :: Monad m => m a -> (a -> m b) -> m b
Give function definitions for the following functions:
(a) the function length :: [a] -> Int, which operates on arbitrary lists
(i) using pattern-matching on the list structure [3]
(ii) using a foldr function, in point-free style [2]
(i) length :: [a] -> Int
length [] = 0
length (x:xy) = 1 + length(xy)
(ii)
length :: [a] -> Int
length = foldr (_ n -> n + 1) 0
(b) the function sum :: [Int] -> Int, which operates on integer lists
(i) using pattern-matching on the list structure [3]
(ii) using a foldr function, in point-free style
(b) (i)
sum :: [Int] -> Int
sum [] = 0
sum (x:xs) = x + sum(xs)
(ii)
sum :: [Int] -> Int
sum = foldr (+) 0