Lesson 1 · Unit 08
Closures and iterators
Functions written in place, and chains of map, filter, sum and collect
What you practise
- Closures and what they capture,
map,filter,sum,collect, chains that do nothing until asked
Try a question from this lesson
Pick one
Something new: the x between the bars is an input, and what follows is done with it. What do you think this prints?
let double = |x| x * 2;
println!("{}", double(21));Hint
Read double as a small function, and the 21 as what goes in.
Correct answer
42
Why
|x| x * 2 is a closure: a function with no name, written in place and kept in a variable. Calling it looks like any function call. The 21 goes in as x, and 21 times 2 comes out.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A closure sees what is around it
A closure is a function written where it is needed. Its inputs sit between two | bars, and its body follows. The types are worked out for you.
Unlike a fn, a closure can use variables from the code around it. This is called capturing. Here the closure captures rate.
let rate = 3;
let cost = |hours| hours * rate;
println!("{}", cost(5));Concept
map and collect
.iter() walks over a vector by reference, as for p in &prices does. What it gives you is called an iterator.
.map(...) takes a closure and runs it on every item. .collect() gathers the results into a new collection. It can build several kinds, so the type on the variable says which one you want.
let prices = vec![10, 20, 30];
let double: Vec<i32> = prices
.iter()
.map(|p| p * 2)
.collect();
println!("{:?}", double);Concept
filter, sum and count
.filter(...) keeps the items for which its closure says true.
.sum() adds up what arrives, and .count() says how many items arrived. As with collect, name the type you want for a sum.
A range such as 1..=6 is an iterator already, so it needs no .iter().
let even: Vec<i32> = (1..=6)
.filter(|n| n % 2 == 0)
.collect();
let total: i32 = (1..=4).sum();
println!("{:?} {}", even, total);9 more exercises in the app
- 3× type the answer
- 2× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.