Higher Order Functions Flashcards
what does map do?
applies a function to every element in a list.
map (+1) [ 1, 3, 5, 7]
[2, 4, 6, 8]
what does filter do?
selects every element in a list that satisfies a predicate
filter :: (a -> Bool) -> [a] -> [a]
filter even [1..10]
[2, 4, 6, 8, 10]
what is the pattern of recursion?
f[] = v
f(x : xs) = x ⊕ f xs
give a recursive definition of sum and its foldr version
recursive:
sum[] = 0
sum(x : xs) = x + sum xs
foldr:
sum = foldr (+) 0
give a recursive definition of and and its foldr version
recursive:
and[] = True
and (x : xs) = x && and xs
foldr:
and = foldr (&&) True
give the foldr definition of length
length = foldr (_ n -> 1 + n) 0
describe the difference between intesionality and extensionality in a sentence
\x.(1+x) is intensionally different from \x.(x+1) but extensionally equal
what does . do?
returns the composition of 2 funstions as a single function
.) :: (b -> c) -> (a -> b) -> (a -> c
f.g = \x -> f(g x)
use . to define odd
odd :: Int -> Bool
odd = not.even
what does all do?
check whether every element satisfies a predicate
all even [2, 4, 6]
True
what does any do?
check whether any element satisfies a predicate
any isSpace “ab c”
True
what does takeWhile do?
selects elements while the predicate holds all elements
takeWhile isAlpha “ab cd”
“ab”
what does dropWhile do?
teh opposite of takeWhile
dropWhile is Alpha “ab cd”
“ cd”
express [fx | x
map f( filter p xs)
what is ad-hoc polymorphism?
overloading