Composing a list of all pairs


#1

I want to know how to do it with rust.
I found (this)[https://stackoverflow.com/questions/11803349/composing-a-list-of-all-pairs] on SO.

val uniquePairs = for {
(x, idxX) <- nums.zipWithIndex
(y, idxY) <- nums.zipWithIndex
if idxX < idxY
} yield (x, y)

val nums = List(1,2,3,4,5)
uniquePairs: List[(Int, Int)] = List((1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5))

Thanks.


#2

Itertools has a combinations function you could use.


#3

Here’s something I hastily cooked up using std only.

#![feature(conservative_impl_trait)]

fn pairs<I: IntoIterator>(x: I) -> impl Iterator<Item = (I::Item, I::Item)>
where
    I::Item: Clone,
    I: Copy,
{
    x.into_iter()
        .enumerate()
        .flat_map(move |t| std::iter::repeat(t.1).zip(x.into_iter().skip(t.0 + 1)))
}

I’m sure there’re better ways. Generators might get it close to the Scala version.