





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






Today ...
foldl :: (a -> b -> a) -> a -> [b] -> a
Prelude> foldl (+) 0 [1, 2, 3] 6
How it works ...
foldl _ acc [] = acc foldl step acc (x:xs) = foldl step (step acc x) xs
foldl (-) 9 [5, 3, 1] → foldl (-) (9 - 5) [3, 1] → foldl (-) ((9 - 5) - 3) [1] → foldl (-) (((9 - 5) - 3) - 1) [] → (((9 - 5) - 3) - 1) → 0
filter :: (a -> Bool) -> [a] -> [a] filter p [] = [] filter p (x:xs) | p x = x : filter p xs | otheriwse = filter p xs
Q: How can filter be defined using foldr? filter’ p xs = foldr step [] xs where step x acc | p x = x : acc | otheriwse = acc
Q: How can filter be defined using foldl? filter’ p xs = foldl step [] xs where step acc x | p x = acc ++ [x] | otherwise = acc
map’ :: (a -> b) -> [a] -> [b] map’ f xs = foldr step [] xs where step x ys = f x : ys
For example ...
map’ odd [1,2,3] → foldr step [] [1,2,3] → step 1 (foldr step [] [2,3]) → odd 1 : (foldr step [] [2,3]) → odd 1 : (step 2 (foldr step [] [3])) → odd 1 : (odd 2 : (foldr step [] [3])) → odd 1 : (odd 2 : (step 3 (foldr step [] []))) → odd 1 : (odd 2 : (odd 3 : (foldr step [] []))) → odd 1 : (odd 2 : (odd 3 : []))
Why care about these higher-order functions?
Instead, we can use lambda expressions (“anonymous” functions)
Prelude> ((x, y, z) -> x) (’a’, ’b’, ’c’) ’a’
Prelude> ((x, y, z) -> y) (’a’, ’b’, ’c’) ’b’
fst3 (x, y, z) = x (x, y, z) -> x
Prelude> :type fst fst3 :: (a, b, c) -> a
Prelude> :type (x, y, z) -> x (x, y, z) -> x :: (a, b, c) -> a
Lambda expressions can be useful w/ higher-order functions:
Prelude> zipWith (\x y -> x^2+y^2) [1..10] [10,9..1] [101,85,73,65,61,61,65,73,85,101]
What we didn’t cover
Prelude> :type (>>=) (>>=) :: (Monad m) => m a -> (a -> m b) -> m b