-
Notifications
You must be signed in to change notification settings - Fork 12.9k
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
Add Iterator::for_each
#42782
Add Iterator::for_each
#42782
Conversation
This works like a `for` loop in functional style, applying a closure to every item in the `Iterator`. It doesn't allow `break`/`continue` like a `for` loop, nor any other control flow outside the closure, but it may be a more legible style for tying up the end of a long iterator chain. This was tried before in rust-lang#14911, but nobody made the case for using it with longer iterators. There was also `Iterator::advance` at that time which was more capable than `for_each`, but that no longer exists. The `itertools` crate has `Itertools::foreach` with the same behavior, but thankfully the names won't collide. The `rayon` crate also has a `ParallelIterator::for_each` where simple `for` loops aren't possible. > I really wish we had `for_each` on seq iterators. Having to use a > dummy operation is annoying. - [@nikomatsakis][1] [1]: https://github.com/nikomatsakis/rayon/pull/367#issuecomment-308455185
(rust_highfive has picked a reviewer for you, use r? to override) |
@bluss I'm curious about your "interesting reasons" to use |
👍 I'm game! @rust-lang/libs, any others have thoughts? |
Works for me! |
I seem to remember there being philosophical objections to this back in the day, but I don't feel particularly strongly. |
Interesting - I'll have to play around with that. And if we do want this
implemented on fold, that needs to happen before stabilization.
|
Woah, |
The benefit of using internal iteration is shown in new benchmarks: test iter::bench_for_each_chain_fold ... bench: 635,110 ns/iter (+/- 5,135) test iter::bench_for_each_chain_loop ... bench: 2,249,983 ns/iter (+/- 42,001) test iter::bench_for_each_chain_ref_fold ... bench: 2,248,061 ns/iter (+/- 51,940)
c5c238b
to
4a8ddac
Compare
src/libcore/iter/iterator.rs
Outdated
/// #![feature(iterator_for_each)] | ||
/// | ||
/// let mut v = vec![]; | ||
/// (0..5).for_each(|x| v.push(x * 100)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i'm not necessarily opposed to the current example you have written, but i find the current example slightly less idiomatic (subjectively) than something like:
let v: Vec<_> = (0..5).map(|x| x * 100).collect();
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure, I was just aiming for something simple and testable. I would definitely use collect or extend for that in real code. Any ideas for something more meaningful?
Similarly, the added benchmarks are just sums.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Any ideas for something more meaningful?
New cookbook contributors usually have problem with consuming functional flow they have built just for the sake of side effects (if they do not wish to obtain any value like in fold
or collect
). Switching to imperative for
just to obtain side effects feels not idiomatic.
Some artificial examples that might not be any better 😸
let (tx, rx) = channel();
(0..5).map(|x| x * 2 + 1).for_each(|x| { tx.send(x).unwrap(); } );
["1", "2", "lol", "baz", "55"]
.iter()
.filter_map(|s| s.parse::<u16>().ok())
.map(|v| v * v)
.for_each(|v| println!("{}", v));
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@budziq I'm glad to hear of more motivation for this!
Your additional examples are OK, but still not testing anything besides successfully compiling. Note that my first example has an assert_eq
with the for-loop result, so we actually get some sanity check that it really works, as trivial as that is. Your channel example could read the rx
side to check the result though.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@cuviper so something like that might be ok?
use std::sync::mpsc::channel;
let (tx, rx) = channel();
(0..5).map(|x| x * 2 + 1).for_each(|x| { tx.send(x).unwrap(); } );
assert_eq!(vec![1, 3, 5, 7, 9], rx.iter().take(5).collect::<Vec<_>>());
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That would work. Do folks like that better? Or perhaps as one more example?
I personally really wanted a |
@steveklabnik I think at that time the main point was that short iterators are probably better off with a Also, the performance benefit of internal iteration via |
I must have done a bad job advocating back then, then. Oh well. |
Ok sounds like there's no reason to not experiment with this at this point, @cuviper if you want to update the example (which I think the comments indicate?) then I'll r+ |
History time!
I would argue that rust-lang/rfcs#1064 (comment) by @nagisa is a decent summary:
The first bullet point has changed. The other ones are still true. |
Thanks for finding more context! My search-fu is apparently weak... I don't think we have to falsify every point against -- only compare them to the points for:
|
In general, I feel like there are a lot of people that do want this, and the people against are just "meh". Anyway, I updated the first example like @budziq's suggestion. |
Obviously I've already been quoted at the top, but I agree with @cuviper that I think the pros outweigh the cons. I think that there is indeed new information since the last time this was discussed:
The two together mean that encouraging the use of The main argument against is basically "TMWTDI", which -- from my POV -- is a good enough reason to stop things without compelling advantages, but not an absolute blocker. I also think one of the points made at the time is at least somewhat false:
I presume that this is referring to |
/// | ||
/// let (tx, rx) = channel(); | ||
/// (0..5).map(|x| x * 2 + 1) | ||
/// .for_each(move |x| tx.send(x).unwrap()); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is the move
necessary here? I would not expect so.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe it's too sneaky, but that lets tx
drop automatically, and then rx
won't block.
@bors: r+ |
📌 Commit e72ee6e has been approved by |
Add `Iterator::for_each` This works like a `for` loop in functional style, applying a closure to every item in the `Iterator`. It doesn't allow `break`/`continue` like a `for` loop, nor any other control flow outside the closure, but it may be a more legible style for tying up the end of a long iterator chain. This was tried before in #14911, but nobody made the case for using it with longer iterators. There was also `Iterator::advance` at that time which was more capable than `for_each`, but that no longer exists. The `itertools` crate has `Itertools::foreach` with the same behavior, but thankfully the names won't collide. The `rayon` crate also has a `ParallelIterator::for_each` where simple `for` loops aren't possible. > I really wish we had `for_each` on seq iterators. Having to use a > dummy operation is annoying. - [@nikomatsakis][1] [1]: https://github.com/nikomatsakis/rayon/pull/367#issuecomment-308455185
☀️ Test successful - status-appveyor, status-travis |
Yay! Now, since I left it unstable with |
Oh, yes, please do. We probably shouldn't have merged yet actually, but no worries! |
See #42987 for that update. |
Hi, I stumbled upon this, but I wondered why This value could be - as it is now - a In code, this could be captured by a trait
I implemented a
Usage could be as follows:
Has this ever been thought about? And if so, why was it apparently rejected? |
@phimuemue There's a form of that built around the |
@phimuemue As an example of "break with a certain item", check out how rust/src/libcore/iter/iterator.rs Lines 1738 to 1746 in ab8b961
(That If you wanted to do the same in your code today†, it can be done with self.try_for_each(move |x| {
if predicate(&x) { Err(x) }
else { Ok(()) }
}).err() † Well, once someone makes a stabilization PR for |
Hello 4 years later! In case anyone else ends up here, the |
This works like a
for
loop in functional style, applying a closure toevery item in the
Iterator
. It doesn't allowbreak
/continue
likea
for
loop, nor any other control flow outside the closure, but it maybe a more legible style for tying up the end of a long iterator chain.
This was tried before in #14911, but nobody made the case for using it
with longer iterators. There was also
Iterator::advance
at that timewhich was more capable than
for_each
, but that no longer exists.The
itertools
crate hasItertools::foreach
with the same behavior,but thankfully the names won't collide. The
rayon
crate also has aParallelIterator::for_each
where simplefor
loops aren't possible.