Iterable.zipWith

François Sarradin fsarradin at gmail.com
Wed May 23 21:53:58 PDT 2012


Hi,

What do you think about adding a kind of zip or zipWith method to the
Iterable interface?

As a reminder, zipWith is a method that mixes two Iterables with a function
in a view to produce a third Iterable. More exactly, zipWith takes elements
of two Iterables one by one and applies a function on them in order to
produce the elements of the third Iterable. In a sense, it is the inverse
operation of tee. Notice that the resulting Iterable has as many elements
as the smallest Iterable.

For example, this is the way you would compose the methods zipWith and
reduce to have a dot product operator:

        Iterable<Double> u = Arrays.asList(1.0, 2.0, 3.0);
        Iterable<Double> v = Arrays.asList(4.0, 5.0, 6.0);

        double dotProduct = u.zipWith(v, (x, y) -> x * y).reduce(0.0, (x,
y) -> x + y);

        assertEquals(32.0, dotProduct, 1e-7);


zipWith is specifically a lazy method. Each element of the result can be
evaluated independently from the other ones.

A signature for zipWith in Iterables might be:

<T1, T2, U> Iterable<U> zipWith(Iterable<T1> elements1, Iterable<T2>
elements2, BiMapper<T1, T2, U> biMapper)


Regards,

françois-


More information about the lambda-dev mailing list