Search code examples
rustmappingapplymapply

Is there a Rust equivalent of R's mapply()?


What is the idiomatic Rust method for R's mapply()? mapply() takes a function, and iterables, and calls the function with the first elements of each iterable as arguments, the second elements, etc.

I am currently using the future_mapply() function in R from the future library to do it in parallel as well, but am finding it to be too slow.

Any help is appreciated.


Solution

  • There is no direct equivalent, as Rust doesn't deal with variadic functions or abstract over tuples of different lengths (better to ignore HLists here). If your number of iterators is fixed, you can use it1.zip(it2).zip(it3).map(|((e1, e2), e3)| f(e1, e2, e3)) or itertools::izip!.

    If all your iterators have the same type (i.e. can be put into a Vec) and the function to be applied is fine with receiving the elements as a Vec, you could do something like

    std::iter::from_fn(move || {
        iter_vec // the vector with your input iterators
            .iter_mut()
            .map(Iterator::next)
            .collect::<Option<Vec<_>>>()
    }).map(f)
    

    Playground

    I think you'll have to describe your problem a bit more for your question to be properly answered.