Reversing a List with Folds
It’s possible to easily implement a reverse function using folds. Try to implement a function that will reverse a list using both foldl and foldr . Which one is simpler? why? Might one be more efficient than the other?
Zipping Lists
The zip function is a special case of a more general function available in Prelude called zipWith . The zipWith function combines two lists according to a function. Consider this implementation of zip in terms of zipWith :
| | λ let zip' = zipWith (,) |
| | λ zip' [1..5] [5,4..1] |
| | [(1,5),(2,4),(3,3),(4,2),(5,1)] |
Implement the zipWith function with and without using list comprehensions. Can you implement zipWith using foldl ?
Implementing concatMap
The concat function joins a list of lists into a single list:
| | concat [[1,2,3],[4,5,6]] |
| | [1,2,3,4,5,6] |
Prelude provides a function named concatMap that can be naively implemented by composing concat and map :
| | concatMap f = concat . map f |
Try implementing concatMap using foldl and foldr . Which one is better? Why?
Thinking about Maps and Folds
Think about the following two lines of code that use map and foldr . When might they do the same thing? When might they differ? How might that change if you used foldl instead of foldr ?
| | λ \ f g -> foldr g 0 . map f |
| | λ \ f g -> foldr (g . f) 0 |
Folds and Infinite lists
You learned in this chapter that you can only use foldr on infinite lists, but not foldl . Try to work manually through calling foldl on an infinite list What happens? What does this tell you about why you can’t use foldl on an infinite list? Are there any other benefits to foldr when dealing with large but finite lists?
Copyright © 2023, The Pragmatic Bookshelf.