Iterator Fold Tracks Min And Max
One fold pass tracks min and max together, instead of walking the data twice with separate min and max calls.
Code
fn main() {
let readings = [42, 18, 133, 7, 95, 61, 18];
// one fold pass tracks both extremes; min()/max() would walk twice
let (min, max) = readings
.iter()
.fold((i32::MAX, i32::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
println!("min: {min}, max: {max}");
// same shape for the argmax: keep the position, not the value
let (best_idx, _) = readings.iter().enumerate().fold(
(0usize, i32::MIN),
|(idx, hi), (i, v)| {
if *v > hi {
(i, *v)
} else {
(idx, hi)
}
},
);
println!("peak at index {best_idx}");
}How it works
Everything happens inside the function main.
Points of care
- Its one and only prerequisite is the language toolchain.
Putting it to use
Entry signature: fn main()
The demo output is labeled (min:, peak at index), so the printed lines read as a trace of the operations that ran.
The core lines of the flow
let (best_idx, _) = readings.iter().enumerate().fold(
(0usize, i32::MIN),
|(idx, hi), (i, v)| {
if *v > hi {
(i, *v)
} else {
(idx, hi)
}
},
);
.fold((i32::MAX, i32::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
Interactive Tools for This Topic
FAQ
- What does Iterator Fold Tracks Min And Max print when run?
- Execute the whole file; each printed line is prefixed with a label like `min:`, `peak at index`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.