CodeBlanks Logo Icon CodeBlanks

Summary - Iterators

Combine map, filter and collect to build a word filter.

Iterators summary

Every iterator implements the Iterator trait: type Item and fn next. Adapters (map, filter, take, zip, enumerate, chain) are lazy and return new iterators; consumers (collect, sum, count, fold, for) produce the result. collect can produce a Vec, String, HashSet or Result depending on the target type.

zip and fold

zip combines two iterators into pairs; fold reduces all elements to a single result starting from an initial value:

let adlar = ["Ali", "Ece"];
let puan = [70, 95];
for (a, p) in adlar.iter().zip(puan.iter()) {
    println!("{a}: {p}");
}
let toplam = puan.iter().fold(0, |acc, p| acc + p);   // 165

sum, max and count are really special cases of fold.

Practice Score table

Combine the arrays ["Ali", "Ece"] and [70, 95] with zip and print each line as ad: puan. Then compute the sum with fold and print toplam N.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let adlar = ["Ali", "Ece"];
    let puan = [70, 95];
    for (a, p) in adlar.iter().zip(puan.iter()) {
        println!("{}: {}", a, p);
    }
    let toplam = puan.iter().fold(0, |acc, p| acc + p);
    println!("toplam {}", toplam);
}

Expected output

Ali: 70
Ece: 95
toplam 165

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is <code>[1, 2, 3].iter().zip(["a", "b"].iter()).count()</code>?

  • 5
  • Panic
  • 2 Correct answer
  • 3

Explanation: zip stops when the shorter iterator runs out.

2 Reduce

Question
let toplam = puan.iter().____(0, |acc, p| acc + p);
Answer
let toplam = puan.iter().fold(0, |acc, p| acc + p);

Explanation: fold takes an initial value and a combining closure.

3 Group summary

Term Meaning
next() One step
map/filter Lazy adapter
collect Collects into a collection
fold Reduces to one value

All lessons in Intermediate