Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ER] Iterator::reduce docs example code #81819

Closed
leonardo-m opened this issue Feb 6, 2021 · 2 comments · Fixed by #102435
Closed

[ER] Iterator::reduce docs example code #81819

leonardo-m opened this issue Feb 6, 2021 · 2 comments · Fixed by #102435
Labels
A-docs Area: documentation for any part of the project, including the compiler, standard library, and tools

Comments

@leonardo-m
Copy link

I think it's better in general for the standard docs to contain examples that are easy to understand, but are also realistic usages of functions and features. An example of this is in slice::binary_search that shows how to insert an item to a sorted vector while maintaining sort order.

So I think the docs of Iterator::reduce could be improved with a more real usage example (to replace the current find_max example). And I think such docs should also say that reduce is useful when your binary operation doesn't have an identity element (or when you don't want to use it for some reason, like efficiency, etc).

@bstrie
Copy link
Contributor

bstrie commented Feb 7, 2021

Given the close similarity to Iterator::fold it should also show an example that demonstrates when they are equivalent, so that people who understand one can understand the other (and hopefully understand the situations in which to use each).

let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
let reduced: Option<i32> = (1..10).reduce(|acc, e| acc + e);
assert_eq!(Some(folded), reduced);

Or alternatively:

let folded = (1..10).fold(0, |acc, e| acc + e);
let reduced = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);
assert_eq!(folded, reduced);

@Nicholas-Baron
Copy link
Contributor

@rustbot label: T-doc.

@rustbot rustbot added the A-docs Area: documentation for any part of the project, including the compiler, standard library, and tools label Feb 14, 2021
@bors bors closed this as completed in b6d1c15 Sep 29, 2022
thomcc pushed a commit to tcdi/postgrestd that referenced this issue Feb 10, 2023
…ple, r=thomcc,vacuus

Improve example of Iterator::reduce

Fixes #81819.

I took your example `@bstrie` from rust-lang/rust#81819 and applied it here.

r? `@thomcc`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-docs Area: documentation for any part of the project, including the compiler, standard library, and tools
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants