# Pre-RFC: Zip.pairmap

**URL:** <https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215>\
**Category:** Uncategorized\
**Created:** [March 2, 2016, 10:22pm UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215 "2016-03-02T22:22:17Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![llogiq](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/llogiq/32/13692_2.png) [@llogiq](https://internals.rust-lang.org/u/llogiq)\
**Post date:** [March 2, 2016, 10:22pm UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/1 "2016-03-02T22:22:18Z")

</div>

In the impl specialization [discussion](https://github.com/rust-lang/rfcs/pull/1210#issuecomment-191305565), I brought forth the idea of having a `.pairmap(_)` method on `Zip`s that map a function of two arguments instead of one argument tuple with two members.

Rationale: One often has predefined functions that take two arguments, and using those functions in a `.zip(_).map(_)` currently needs a closure to unpack the argument tuple. This obviously makes the code a little less readable.

If there’s interest, I could write up an RFC, and probably an implementation.

---

<div class="post-metadata">

**Author:** ![abonander](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/abonander/32/1284_2.png) [@abonander](https://internals.rust-lang.org/u/abonander)\
**Post date:** [March 2, 2016, 11:30pm UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/2 "2016-03-02T23:30:56Z")

</div>

It’s probably stupid (potentially frustrating and bug-inducing implicit behavior), but what about `impl <F: FnMut(A, B) -> C> FnMut((A, B)) -> C for F` that unpacks the tuple? Or a wrapper type that does the same thing?

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cuviper/32/1897_2.png) [@cuviper](https://internals.rust-lang.org/u/cuviper)\
**Post date:** [March 3, 2016, 12:10am UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/3 "2016-03-03T00:10:02Z")

</div>

I think it would be frustrating to be incomplete – what about `pair_flat_map`, `pair_filter`, `pair_find`, etc.? Does `pair_zip` on a third iterator now result in a triplet?

At least @abonander’s `impl` would be more general. That could naturally extend to `Fn((A, B, C)) -> D` and on, but I don’t know if we’d want to go so far as supporting nested tuples, like `.zip.zip.map` needing `Fn(((A, B), C)) -> D`.

---

<div class="post-metadata">

**Author:** ![eddyb](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/eddyb/32/8411_2.png) [@eddyb](https://internals.rust-lang.org/u/eddyb)\
**Post date:** [March 4, 2016, 11:35am UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/4 "2016-03-04T11:35:14Z")

</div>

The reason we have first-class tuples and destructuring is _precisely_ so that we don’t need to cater to special cases like pairs or whatnot.

`.map(|(a, b)| ...)` works, what’s even the point of adding less obvious magic for golfing?

---

<div class="post-metadata">

**Author:** ![bluss](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bluss/32/2264_2.png) [@bluss](https://internals.rust-lang.org/u/bluss)\
**Post date:** [March 4, 2016, 11:38am UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/5 "2016-03-04T11:38:15Z")

</div>

I fully sympathize with trying to solve this problem.

Closures using `(a, b)` arguments come up a lot, and anything to reduce the amount of punctuation you need to type to work with it would be great.

---

<div class="post-metadata">

**Author:** ![leonardo](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/leonardo/32/1344_2.png) [@leonardo](https://internals.rust-lang.org/u/leonardo)\
**Post date:** [March 4, 2016, 2:38pm UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/6 "2016-03-04T14:38:08Z")

</div>

In Haskell there’s a very handy function named zipWith, that I’ve often missed in the D standard library:

[http://zvon.org/other/haskell/Outputprelude/zipWith\_f.html](http://zvon.org/other/haskell/Outputprelude/zipWith_f.html)

Usage examples:

```
let a = [1, 2, 3];
let b = [10, 20, 30];

struct V(u32, u32);
a.iter().zip(b).zipWith(V)
==> 
V(1,10), V(2,20), V(3,30)

a.iter().zip(b).zipWith(add)
==>
11, 22, 33
```

---

<div class="post-metadata">

**Author:** ![Florob](https://avatars.discourse-cdn.com/v4/letter/f/96bed5/32.png) [@Florob](https://internals.rust-lang.org/u/Florob)\
**Post date:** [March 4, 2016, 5:28pm UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/7 "2016-03-04T17:28:35Z")

</div>

I played around a bit with this general train of thought, to get an idea if I like it.

The first result is a `unpack_map()` for `Iterator`s over n-ary tuples, that will call an n-ary function with the contents of the tuple:

```
#![feature(unboxed_closures, fn_traits)]

struct UnpackMap<I, F> {
    iter: I,
    f: F
}

impl<I: Iterator, F: FnMut<I::Item>> Iterator for UnpackMap<I, F> {
    type Item = F::Output;

    fn next(&mut self) -> Option<F::Output> {
        self.iter.next().map(|x| (&mut self.f).call_mut(x))
    }
}

trait IteratorExt : Iterator {
    fn unpack_map<F>(self, f: F) -> UnpackMap<Self, F>
        where Self: Sized, F: FnMut<Self::Item>
    {
        UnpackMap { iter: self, f: f }
    }
}

impl<T> IteratorExt for T where T: Iterator {}

```

The second is an adaptor as suggested by @abonander:

```
struct PackedFn<F> {
    f: F
}

impl<Args, F: FnOnce<Args>> FnOnce<(Args,)> for PackedFn<F> {
    type Output = F::Output;

    extern "rust-call" fn call_once(self, a: (Args,)) -> F::Output {
        self.f.call_once(a.0)
    }
}

impl<Args, F: FnMut<Args>> FnMut<(Args,)> for PackedFn<F> {
    extern "rust-call" fn call_mut(&mut self, a: (Args,)) -> F::Output {
        (&mut self.f).call_mut(a.0)
    }
}

impl<Args, F: Fn<Args>> Fn<(Args,)> for PackedFn<F> {
    extern "rust-call" fn call(&self, a: (Args,)) -> F::Output {
        (&self.f).call(a.0)
    }
}

fn pack<Args, F>(f: F) -> PackedFn<F> where F: FnOnce<Args> {
    PackedFn { f: f }
}

```

Usage examples are as follows:

```
#[derive(Debug)]
struct V(u32, u32, u32);

fn main() {
    let a = vec![(1, 2, 3), (4, 5, 6), (7, 8, 9)];
    
    for x in a.clone().into_iter().unpack_map(V) {
        println!("{:?}", x);
    }
    
    for x in a.into_iter().map(pack(V)) {
        println!("{:?}", x);
    }
}

```

My general impression is that both are workable (with the current implementation of the `Fn` traits), but not worthwhile to add. In particular because what most people really want for higher arity, is something that will accept `((T, U), V)`.

---

<div class="post-metadata">

**Author:** ![jimb](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jimb/32/1184_2.png) [@jimb](https://internals.rust-lang.org/u/jimb)\
**Post date:** [March 7, 2016, 7:44am UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/8 "2016-03-07T07:44:31Z")

</div>

Another approach would be to have an operator that takes a function of N arguments and produces a function on N-tuples. That could be mapped easily. The idea generalizes naturally to higher arities. As a prefix `/` operator:

```rust
    let i1 = (0..20).step_by(2);
    let i2 = 5..15;
    let m : Vec<i32> = i1.zip(i2).map(/std::cmp::min).collect();

    assert_eq!(m, vec![0,2,4,6,8,10,11,12,13,14]);

```

---

<div class="post-metadata">

**Author:** ![eternaleye](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/eternaleye/32/3505_2.png) [@eternaleye](https://internals.rust-lang.org/u/eternaleye)\
**Post date:** [March 7, 2016, 8:29am UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/9 "2016-03-07T08:29:27Z")

</div>

I’ll note that, while unstable, the `Fn*` traits natively operate on tuples:

```rust
#![feature(fn_traits)]
#![feature(unboxed_closures)]

use std::ops::FnOnce;

fn foo<T, F: FnOnce<T>>( x: T, f: F ) -> F::Output {
    f.call_once( x )
}

fn main() {
    println!("{:?}", foo( (1, 2), move |x, y| (x + 1, y + 3) ) );
}

```

The above code prints “2, 5” on Nightly as-is: [https://play.rust-lang.org/?gist=88d3d5fbb8cca49256c7&version=nightly](https://play.rust-lang.org/?gist=88d3d5fbb8cca49256c7&version=nightly)

Once that’s stabilized, which would be useful in its own right, special-casing anything of the sort would be rendered obsolete (save perhaps `impl<T, F: Fn<T>> Fn<(T)> for F { ... }` across the `Fn*` traits, or the nearest coherency allows, perhaps with Into - should have essentially zero runtime overhead).

---

<div class="post-metadata">

**Author:** ![eddyb](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/eddyb/32/8411_2.png) [@eddyb](https://internals.rust-lang.org/u/eddyb)\
**Post date:** [March 7, 2016, 9:20am UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/10 "2016-03-07T09:20:31Z")

</div>

Note that it’s likely not going to be ever stabilized without generalized tuple manipulation and/or “variadic generics”.

---

<div class="post-metadata">

**Author:** ![m4rw3r](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/m4rw3r/32/1238_2.png) [@m4rw3r](https://internals.rust-lang.org/u/m4rw3r)\
**Post date:** [March 7, 2016, 10:03am UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/11 "2016-03-07T10:03:49Z")

</div>

This crate provides a zip\_with implementation: [https://crates.io/crates/zipWith](https://crates.io/crates/zipWith)

Personally I think an iterator adapter like that should belong in std because this pattern is common with two iterators.

---

<div class="post-metadata">

**Author:** ![eddyb](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/eddyb/32/8411_2.png) [@eddyb](https://internals.rust-lang.org/u/eddyb)\
**Post date:** [March 27, 2016, 3:06pm UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/12 "2016-03-27T15:06:47Z")

</div>

It’s _literally_ `a.zip(b).map(|(a, b)| ...)`.  
This is pretty much left-pad levels of usefulness.

However, it looks like that crate has a very specific usecase, and that is a workaround for the need of `-> impl Iterator`, _not just sugar_.

Moving forward with `impl Trait` is a much better approach than stabilizing another adapter in libstd.

---

<div class="post-metadata">

**Author:** ![llogiq](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/llogiq/32/13692_2.png) [@llogiq](https://internals.rust-lang.org/u/llogiq)\
**Post date:** [March 28, 2016, 7:26am UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/13 "2016-03-28T07:26:33Z")

</div>

I fully agree – if we can have `impl Trait` within a reasonable time frame, I won’t slow you folks down by asking for band-aids like this. 😄

---

<div class="post-metadata">

**Author:** ![llogiq](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/llogiq/32/13692_2.png) [@llogiq](https://internals.rust-lang.org/u/llogiq)\
**Post date:** [March 25, 2019, 8:25am UTC](https://internals.rust-lang.org/t/pre-rfc-zip-pairmap/3215/14 "2019-03-25T08:25:50Z")

</div>

Closed on March 25, 2019, 8:25am UTC

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