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

Add Iterator::for_each #42782

Merged
merged 3 commits into from
Jun 30, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/doc/unstable-book/src/library-features/iterator-for-each.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# `iterator_for_each`

The tracking issue for this feature is: [#TBD]

[#TBD]: https://github.com/rust-lang/rust/issues/TBD

------------------------

To call a closure on each element of an iterator, you can use `for_each`:

```rust
#![feature(iterator_for_each)]

fn main() {
(0..10).for_each(|i| println!("{}", i));
}
```
47 changes: 47 additions & 0 deletions src/libcore/benches/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,50 @@ fn bench_zip_add(b: &mut Bencher) {
add_zip(&source, &mut dst)
});
}

/// `Iterator::for_each` implemented as a plain loop.
fn for_each_loop<I, F>(iter: I, mut f: F) where
I: Iterator, F: FnMut(I::Item)
{
for item in iter {
f(item);
}
}

/// `Iterator::for_each` implemented with `fold` for internal iteration.
/// (except when `by_ref()` effectively disables that optimization.)
fn for_each_fold<I, F>(iter: I, mut f: F) where
I: Iterator, F: FnMut(I::Item)
{
iter.fold((), move |(), item| f(item));
}

#[bench]
fn bench_for_each_chain_loop(b: &mut Bencher) {
b.iter(|| {
let mut acc = 0;
let iter = (0i64..1000000).chain(0..1000000).map(black_box);
for_each_loop(iter, |x| acc += x);
acc
});
}

#[bench]
fn bench_for_each_chain_fold(b: &mut Bencher) {
b.iter(|| {
let mut acc = 0;
let iter = (0i64..1000000).chain(0..1000000).map(black_box);
for_each_fold(iter, |x| acc += x);
acc
});
}

#[bench]
fn bench_for_each_chain_ref_fold(b: &mut Bencher) {
b.iter(|| {
let mut acc = 0;
let mut iter = (0i64..1000000).chain(0..1000000).map(black_box);
for_each_fold(iter.by_ref(), |x| acc += x);
acc
});
}
46 changes: 46 additions & 0 deletions src/libcore/iter/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,52 @@ pub trait Iterator {
Map{iter: self, f: f}
}

/// Calls a closure on each element of an iterator.
///
/// This is equivalent to using a [`for`] loop on the iterator, although
/// `break` and `continue` are not possible from a closure. It's generally
/// more idiomatic to use a `for` loop, but `for_each` may be more legible
/// when processing items at the end of longer iterator chains. In some
/// cases `for_each` may also be faster than a loop, because it will use
/// internal iteration on adaptors like `Chain`.
///
/// [`for`]: ../../book/first-edition/loops.html#for
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iterator_for_each)]
///
/// let mut v = vec![];
/// (0..5).for_each(|x| v.push(x * 100));
Copy link
Member

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();

Copy link
Member Author

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.

Copy link
Contributor

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));

Copy link
Member Author

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.

Copy link
Contributor

@budziq budziq Jun 27, 2017

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<_>>());

Copy link
Member Author

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?

///
/// let mut v2 = vec![];
/// for x in 0..5 { v2.push(x * 100); }
///
/// assert_eq!(v, v2);
/// ```
///
/// For such a small example, the `for` loop is cleaner, but `for_each`
/// might be preferable to keep a functional style with longer iterators:
///
/// ```
/// #![feature(iterator_for_each)]
///
/// (0..5).flat_map(|x| x * 100 .. x * 110)
/// .enumerate()
/// .filter(|&(i, x)| (i + x) % 3 == 0)
/// .for_each(|(i, x)| println!("{}:{}", i, x));
/// ```
#[inline]
#[unstable(feature = "iterator_for_each", issue = "0")]
fn for_each<F>(self, mut f: F) where
Self: Sized, F: FnMut(Self::Item),
{
self.fold((), move |(), item| f(item));
}

/// Creates an iterator which uses a closure to determine if an element
/// should be yielded.
///
Expand Down