# Add "iterate with separators" iterator function

**URL:** <https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781>\
**Category:** libs\
**Created:** [May 4, 2023, 4:59am UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781 "2023-05-04T04:59:31Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![nyurik](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nyurik/32/9660_2.png) [@nyurik](https://internals.rust-lang.org/u/nyurik)\
**Post date:** [May 4, 2023, 4:59am UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/1 "2023-05-04T04:59:31Z")

</div>

I often see the need to handle "items with separators". Some are so common that we have specific functions like [join()](https://docs.rs/itertools/latest/itertools/fn.join.html) and [intersperse](https://docs.rs/itertools/latest/itertools/fn.intersperse.html), but there is no "generic" functional pattern. I even asked about it on [stackoverflow](https://stackoverflow.com/questions/76157860/optimal-code-pattern-to-print-comma-separated-lists-in-rust), but no good solutions were given, so I would like to propose a new function:

```rust
let items = vec!["Hello", "World", "!"];
items.foreach_with_separator(
    |elem| print!("{elem}"), // This is called on each element
    || print!(", "), // This is called "between" each element
);

```

This approach allows arbitrary complex element handling, as well as any kind of separation logic, without duplicating element handling -- I often see it duplicated for the first item and for subsequent ones (or all\_items + last item). This will also avoid the need to maintain the boolean state of "is this the first element or not".

The separator callback might benefit from a few additional params:

- index parameter counting separator callback invocations - `|_idx: usize| print!(", "),`
- neighboring elements, e.g. `|_elem_before: &T, _elem_after: &T| print!(", "),`
- all 3 params `|_idx, _elem_before, _elem_after| print!(", "),`

Even more generically, we may want to introduce an accumulator version (this example re-implements the `join()` function):

```rust
let items = vec!["Hello", "World", "!"];
let result = items.fold_with_separator(
    String::new(),
    |accumulator, elem| accumulator.append(elem),
    |accumulator| accumulator.append(", ")
);

```

## Alternatives

[intersperse](https://docs.rs/itertools/latest/itertools/fn.intersperse.html) allows a similar but more convoluted/verbose way to do this, and only work for Clone-able items. In this example, it converts values to Options, with `None` being the separator, thus it might bloat the binary if `T::clone()` is not used anywhere else, and compiler doesn't realize it will never get called in this code. Note that this function has also been implemented as unstable in the stdlib.

```rust
let items = vec!["foo", "bar", "baz"];
for v in items.iter().map(|v| Some(v)).intersperse(None) {
    if let Some(v) = v {
        print!("{v}")
    } else {
        print!(", ")
    }
}

```

`enumerate()` offers a more classical way to do this:

```rust
let items = vec!["foo", "bar", "baz"];
for (idx, v) in items.iter().enumerate() {
    if idx > 0 {
        print!(", ")
    }
    print!("{v}")
}

```

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quinedot/32/7294_2.png) [@quinedot](https://internals.rust-lang.org/u/quinedot)\
**Post date:** [May 4, 2023, 5:41am UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/2 "2023-05-04T05:41:55Z")

</div>

[Like so?](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1874be3f6078f4718cffc7d2d2b84503)

> [@nyurik](#):
>
> - index parameter counting separator callback invocations - `|_idx: usize| print!(", "),`
> - neighboring elements, e.g. `|_elem_before: &T, _elem_after: &T| print!(", "),`
> - all 3 params `|_idx, _elem_before, _elem_after| print!(", "),`

You can't give away your ownership to the previous item by calling the item closure and then pass a reference to it to the separator closure in the general case.

---

<div class="post-metadata">

**Author:** ![nyurik](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nyurik/32/9660_2.png) [@nyurik](https://internals.rust-lang.org/u/nyurik)\
**Post date:** [May 4, 2023, 6:10am UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/3 "2023-05-04T06:10:06Z")

</div>

@quinedot this is exactly what I had in mind! I added a simple [testcase](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9e5c7de2b9264ff064c0e83001708754) to your implementation.

What do you think about the more generic fold pattern? And even more important - what would be the best way to be considered for this to become a part of stdlib?

I am not certain I understood your point about giving ownership - are you saying an iterator cannot call my callbacks with references more than once? I may need to dig deeper into that. In any case, those might be nice to have but not required.

---

<div class="post-metadata">

**Author:** ![2e71828](https://avatars.discourse-cdn.com/v4/letter/2/3e96dc/32.png) [@2e71828](https://internals.rust-lang.org/u/2e71828)\
**Post date:** [May 4, 2023, 7:08am UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/4 "2023-05-04T07:08:54Z")

</div>

I can think of a couple of possibilities for iterator adapters that might make this easier without necessarily directly solving the problem:

- `delay(n)` to prepend a string of `None`s to an iterator:

```rust
    let items = vec!["foo", "bar", "baz"];
    for (sep, v) in zip(repeat(", ").delay(1), items) {
        if let Some(s) = sep {
            print!("{s}")
        }
        print!("{v}")
    }

```

> **[Rust Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=2e8ca5589612e3e92042cecebf0daa4d)**
>
> A browser interface to the Rust compiler to experiment with the language

- Add some adapters to make `Peekable` more usable:

```rust
    let items = vec!["foo", "bar", "baz"];
    for (x, has_tail) in items.iter().peekable().map_peek(|x, n| (x, n.is_some())) {
        let sep = if has_tail { ", " } else { "" };
        print!("{x}{sep}");
    }

```

> **[Rust Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=8dbb668f138370da560ded94ae03e2d1)**
>
> A browser interface to the Rust compiler to experiment with the language

(or)

```rust
    let items = vec!["foo", "bar", "baz"];
    items.iter().peekable().for_each_peek(|x, next| {
        let sep = match next {
            Some(_) => ", ",
            None => ""
        };
        print!("{x}{sep}");
    });

```

> **[Rust Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=1a0d0e409c973e38f44aef77480fee78)**
>
> A browser interface to the Rust compiler to experiment with the language

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quinedot/32/7294_2.png) [@quinedot](https://internals.rust-lang.org/u/quinedot)\
**Post date:** [May 4, 2023, 7:30am UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/5 "2023-05-04T07:30:55Z")

</div>

> [@nyurik](#):
>
> And even more important - what would be the best way to be considered for this to become a part of stdlib?

Either an [ACP](https://std-dev-guide.rust-lang.org/feature-lifecycle/api-change-proposals.html) or just a PR with the implementation behind some feature gate (which may be accepted, rejected, or result in a "file an ACP" response).

A team member may have more specific advice (I'm not a team member).

> [@nyurik](#):
>
> I am not certain I understood your point about giving ownership - are you saying an iterator cannot call my callbacks with references more than once? I may need to dig deeper into that. In any case, those might be nice to have but not required.

I mean there's no way to support the pattern of

```rust
main_item_closure_that_takes_ownership(item_0);
seperator_closure_that_takes_references(&item_0, &item_1);

```

Because you've given away ownership of `item_0` (unless it implements `Copy`, or you `Clone` it, etc), so there's no way for you to preserve a reference to it.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [May 4, 2023, 4:08pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/6 "2023-05-04T16:08:57Z")

</div>

I think this is unlikely for `core`. Particular combinations of things usually aren't added, especially when it's just consuming it, not an adapter. The usual response is that you can just put the function in your own code if you want it.

The `enumerate` approach is fine, or [`Itertools::with_position`](https://docs.rs/itertools/latest/itertools/trait.Itertools.html#method.with_position) if you want to do more complicated stuff.

In general, I'm not a fan of multi-closure APIs. For example, you can't have both of them push into a `&mut String`, because you can't give both of the closures the mutable reference at the same time. When it's one closure with a branch, though -- like with `.enumerate().for_each(…)` -- you don't hit that problem.

---

<div class="post-metadata">

**Author:** ![nyurik](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nyurik/32/9660_2.png) [@nyurik](https://internals.rust-lang.org/u/nyurik)\
**Post date:** [May 4, 2023, 6:42pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/7 "2023-05-04T18:42:20Z")

</div>

The `with_position` API is interesting, thx, but it might be a bit too cumbersome to use because one would have to list all use cases to consume the value, i.e. `with_position(|v| match v { First(v) => ..., Middle(v) => ..., Last(v) => ..., Only(v) => ...})` is a pain to write frequently - so won't be used as much. And good feedback about the multi-closure aspect.

So perhaps a special case of the intersperse API instead would address the same issue better?

```rust
for v in elements.iter().intersperse_nones() {
    if let Some(v) = v { print!("{v}") } else { print!(", ") }
}

```

Note that `intersperse` is a nightly API at the moment, and requires an extra map and a param to get the same result:

```rust
for v in elements.iter().map(|x| Some(x)).intersperse(None) {
    if let Some(v) = v { print!("{v}") } else { print!(", ") }
}

```

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [May 4, 2023, 6:56pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/8 "2023-05-04T18:56:23Z")

</div>

> [@nyurik](#):
>
> because one would have to list all use cases to consume the value, i.e. `with_position(|v| match v { First(v) => ..., Middle(v) => ..., Last(v) => ..., Only(v) => ...})` is a pain to write frequently

You don't, because there's `Position::into_inner` for that.

So you could write something like

```rust
    if !matches(x, Position::First(_)) { ... }
    handle(x.into_inner());

```

if you want.

---

<div class="post-metadata">

**Author:** ![jongiddy](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jongiddy/32/1163_2.png) [@jongiddy](https://internals.rust-lang.org/u/jongiddy)\
**Post date:** [May 5, 2023, 6:39pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/9 "2023-05-05T18:39:27Z")

</div>

I tend to use `std::iter::once` for these kind of tasks.

```rust
std::iter::once("")
    .chain(std::iter::repeat(", "))
    .zip(items.iter())
    .for_each(|(sep, elem)| print!("{sep}{elem}"));

```

or

```rust
let mut sep = std::iter::once("");
items.iter().for_each(|elem| print!("{}{}", sep.next().unwrap_or(", "), elem));

```

It's particularly nice when the first separator is a non-empty string (e.g. `?param1&param2&param3`)

---

<div class="post-metadata">

**Author:** ![nyurik](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nyurik/32/9660_2.png) [@nyurik](https://internals.rust-lang.org/u/nyurik)\
**Post date:** [May 5, 2023, 6:59pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/10 "2023-05-05T18:59:11Z")

</div>

Thanks for all the suggestions. I guess the most important aspect in addition to "intent clarity" is to ensure compiler is able to optimize away all the abstractions, and produce the most performant and small code possible. I will try to play with some micro-benchmarking too to see if any of the suggested patterns perform as well as a new dedicated function.

---

<div class="post-metadata">

**Author:** ![Sky9](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/sky9/32/12959_2.png) [@Sky9](https://internals.rust-lang.org/u/Sky9)\
**Post date:** [May 6, 2023, 6:09pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/11 "2023-05-06T18:09:10Z")

</div>

In alternatives you mention the (unstable) `intersperse`. Under the same feature gate is [`intersperse_with`](https://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.intersperse_with), which lifts the clone limitation by taking a closure instead.

---

<div class="post-metadata">

**Author:** ![nyurik](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nyurik/32/9660_2.png) [@nyurik](https://internals.rust-lang.org/u/nyurik)\
**Post date:** [May 6, 2023, 7:46pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/12 "2023-05-06T19:46:57Z")

</div>

Thanks @Sky9, I didn't notice it, but it seems it would still be somewhat un-ergonomic (not certain of how optimal the resulting binary will be, also needs testing) ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=af4fc3e243ca53ea70d184b6ced8e5f1))

```rust
let elements = vec!["a", "b", "c"];
for v in elements.iter().map(|x| Some(x)).intersperse_with(|| None) {
    if let Some(v) = v { print!("{v}") } else { print!(", ") }
}

```

---

<div class="post-metadata">

**Author:** ![8573](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/8573/32/4913_2.png) [@8573](https://internals.rust-lang.org/u/8573)\
**Post date:** [May 6, 2023, 8:19pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/13 "2023-05-06T20:19:01Z")

</div>

This might not be useful more generally, but that `if`-`let`-`else` could be shortened to `print!("{}", v.unwrap_or(&", "))`.

Edited to add: The `for` loop could be

```rust
for v in elements.iter().intersperse(&", ") {
    print!("{v}")
}

```

That seems too simple, so I guess it likely isn't useful.

---

<div class="post-metadata">

**Author:** ![nyurik](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nyurik/32/9660_2.png) [@nyurik](https://internals.rust-lang.org/u/nyurik)\
**Post date:** [May 7, 2023, 7:18pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/14 "2023-05-07T19:18:08Z")

</div>

I have ran some [basic benchmarks](https://gist.github.com/nyurik/e702c1aa940b09f2798fbd94596650a4) on 4 variants. The dedicated iterator function that converts `Iter::Item` into `Option<Iter::Item>`, and injects `None` as a separator is ~2.5 times faster than the other methods proposed here (raw speed of the iteration itself, not counting additional processing like writing to a string buffer in the second benchmark)

All times are in milliseconds (µs)

#### Simple iteration

each value is called with `black_box(v)`, and each separator is `black_box(0)`

```
run #1: min/avg/max run #2: min/avg/max
intersperse_nones [0.5622 0.5627 0.5633] [0.5623 0.5627 0.5633]
foreach [0.5594 0.5598 0.5603] [0.5591 0.5592 0.5594]
for [0.7722 0.7742 0.7766] [0.7716 0.7719 0.7724]
intersperse_with [1.4002 1.4163 1.4411] [1.3987 1.3993 1.3999]
intersperse [1.4012 1.4016 1.4021] [1.4007 1.4008 1.4009]
with_position [1.1193 1.1194 1.1195] [1.1195 1.1197 1.1201]
```

#### make a string

Convert a vec of numbers to a comma-separated string of numbers -- similar to join(",")

```
run #1: min/avg/max run #2: min/avg/max
intersperse_nones-join [18.238 18.521 18.902] [17.775 17.817 17.870]
foreach-join [17.624 17.662 17.708] [17.628 17.665 17.711]
for-join [17.803 17.816 17.832] [17.781 17.792 17.807]
intersperse_with-join [19.293 20.109 21.137] [18.551 18.590 18.653]
intersperse-join [18.579 18.647 18.753] [18.397 18.445 18.502]
with_position-join [18.394 18.469 18.592] [18.275 18.320 18.376]
```

---

<div class="post-metadata">

**Author:** ![nyurik](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nyurik/32/9660_2.png) [@nyurik](https://internals.rust-lang.org/u/nyurik)\
**Post date:** [May 8, 2023, 6:35am UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/15 "2023-05-08T06:35:25Z")

</div>

Benchmarks and their results were heavily updated in the prior comment. I also added a benchmark for the @scottmcm suggestion (had to fix it a bit). Please let me know if additional approaches should be tried, or if the benchmarks themselves can be made more accurate. So far it seems like adding a dedicated function would significantly boost performance for these types of workload.

---

<div class="post-metadata">

**Author:** ![jongiddy](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jongiddy/32/1163_2.png) [@jongiddy](https://internals.rust-lang.org/u/jongiddy)\
**Post date:** [May 8, 2023, 12:40pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/16 "2023-05-08T12:40:49Z")

</div>

I'm not sure that I would expect this to be performance-sensitive, but the benchmark to beat, both in timing and clarity, is:

```rust
let mut use_sep = false;
elements.iter().for_each(|v| {
    if use_sep {
        handle_box(None);
    } else {
        use_sep = true;
    }
    handle_box(Some(v));
});

```

---

<div class="post-metadata">

**Author:** ![nyurik](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nyurik/32/9660_2.png) [@nyurik](https://internals.rust-lang.org/u/nyurik)\
**Post date:** [May 8, 2023, 5:42pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/17 "2023-05-08T17:42:34Z")

</div>

@jongiddy thx, I added two more benchmarks - one with a `for v in elem.iter()` and one with `elem.iter().for_each(...)`. The results are somewhat surprising:

- All results fluctuate a few percent in each run
- For simple iter, the `intersperse_nones` and `foreach` tend to be nearly identical (foreach being about 0.1% faster?)
- For simple iter, the `for` loop is somehow about 35% slower (?!?)
- When writing a CSV string, the performance of all 3 are within 1% of each other

So it seems there is still a valid case to introduce a new iter function? Consider these two closest contenders:

```rust
for v in elements.iter().intersperse_nones() {
    if let Some(v) = v {
        black_box(v);
    } else {
        black_box(0);
    }
}

let mut use_sep = false;
elements.iter().for_each(|v| {
    if use_sep {
        black_box(0);
    } else {
        use_sep = true;
    }
    black_box(v);
});

```

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [May 8, 2023, 5:55pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/18 "2023-05-08T17:55:03Z")

</div>

> [@nyurik](#):
>
> For simple iter, the `for` loop is somehow about 35% slower (?!?)

Yes, internal iteration is sometimes faster. Usual link: [Rust’s iterators are inefficient, and here’s what we can do about it. | by Veedrac | Medium](https://medium.com/@veedrac/rust-is-slow-and-i-am-the-cure-32facc0fdcb)

> [@nyurik](#):
>
> When writing a CSV string, the performance of all 3 are within 1% of each other

This sounds like it's probably within noise to me. And the ones that are nanobenchmarks I just don't really trust -- sticking a black box in the middle of a loop makes it non-representative of the actual cost of the optimized loop.

Note that performance usually isn't a sufficient reason to introduce a new iterator to std -- if it can be written outside it, like you have demonstrated is possible here, then the default is still that it should be a crate.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/system/32/14092_2.png) [@system](https://internals.rust-lang.org/u/system)\
**Post date:** [August 6, 2023, 5:55pm UTC](https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/19 "2023-08-06T17:55:18Z")

</div>

Closed on August 6, 2023, 5:55pm UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
