Join method for all iterators


#1

So I have recently had a situation where i had an iterator over String, and I wanted to join them with a space in the middle. it turned out to be really awkward.

I was surprised to be unable to find a join method on the iterator that did the job. I did find std::slice::SliceConcatExt But that seems to be rather specific on slices, and I didn’t want to make one.

Rather than solve the problem for my specific case, I remembered that Premature Generalization is the root of all Evil, and so of course that’s what I did.

https://play.rust-lang.org/?gist=9e957c61251d082abe4907bfd3d75839&version=stable&mode=debug&edition=2015

The above is a joining iterator trait called Joinable which works on almost anything. It clones and repeats the joining parameyer and alternates with the original iterator starting and ending with values from the original iterator.

Could this / or something like it have a place in the stdlib?


#2

I agree it’s a missing functionality. There were many occasions when I wished to have join() on an iterator of strings.

I was thinking about implementing a collect-like method on Iterator of elements like AsRef<str> or Display.

Your solution is interesting. It doesn’t actually do the joining, but it’s more like interleaving.


#3

I think the itertools crate already has a join method: https://docs.rs/itertools/0.7.2/itertools/fn.join.html Seems like IntoIterator is good enough for it, so I’m not sure a new Joinable trait buys us anything.


#4

yeah, I pondered writing using some actual form of interleave on two separate iterators and then making this a specific case,where the iterator returns the same thing.

I think that might have been too generalized even for me.


#5

ah, that’s what I was looking for lol. Coulda saved me some work there. I probably wouldn’t have bothered writing this if i’d found that first.

Still: this version chains on iterators, so that might still have value.

Maybe I’ll make it a crate instead.


#6

I’m not sure I would call your function on the playground “join”. If I understand correctly, it turns

["hello", "world", "and", "goodnight"]

into

["hello", ",", "world", ",", "and", ",", "goodnight"]

, right? This sounds like Itertools::intersperse.


#7

yup it sounds exactly like that. and looking at the code it does the job better too.