8

I am writing a function that does piecewise multiplication of two arrays.

    xs.iter()
        .zip(ys).map(|(x, y)| x * y)
        .sum()

In some other languages, I can pass (*) as a function to map. Does Rust have this feature?

0

3 Answers 3

15

Nnnyes. Sorta kinda not really.

You can't write an operator as a name. But most operators are backed by traits, and you can write the name of those, so a * b is effectively Mul::mul(a, b), and you can pass Mul::mul as a function pointer.

But that doesn't help in this case because Iterator::map is expecting a FnMut((A, B)) -> C, and the binary operators all implement FnMut(A, B) -> C.

Now, you could write an adapter for this, but you'd need one for every combination of arity and mutability. And you'd have to eat a heap allocation and indirection or require a nightly compiler.

Or, you could write your own version of Iterator::map on an extension trait that accepts higher arity functions for iterators of tuples... again, one for each arity...

Honestly, it's simpler to just use a closure.

10

Rust does not have any syntax to pass infix operators, mostly because it is redundant anyway.

In Rust, each operator maps to a trait: * maps to the std::ops::Mul trait, for example.

Therefore, using * directly should be using std::ops::Mul::mul:

xs.iter().zip(ys).map(Mul::mul).sum();

However there are several difficulties:

  1. Generally, iterators yield references while Mul is implemented for plain values,
  2. Mul::mul expects two arguments, xs.zip(ys) yields a single element (a tuple of two elements).

So, you need to go from reference to value and then "unpack" the tuple and... it ends up being shorter to use a closure.

3

No. The * operator is implemented in std::Ops::Mul, but it can't be used directly:

use std::ops::Mul::mul;

fn main() {
    let v1 = vec![1, 2, 3];
    let v2 = vec![1, 2, 3];

    println!("{:?}", v1.iter().zip(v2).map(|(x, y)| mul).collect());
}

Will result in the following error:

error[E0253]: `mul` is not directly importable
 --> <anon>:1:5
  |
1 | use std::ops::Mul::mul;
  |     ^^^^^^^^^^^^^^^^^^ cannot be imported directly

You could introduce your own function using the * operator, but there wouldn't be much added value :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.