Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rust support using an infix operator as a function?

Tags:

rust

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?

like image 325
colinfang Avatar asked Jun 13 '17 11:06

colinfang


People also ask

What is an infix function?

Infix notation is the notation commonly used in arithmetical and logical formulae and statements. It is characterized by the placement of operators between operands—"infixed operators"—such as the plus sign in 2 + 2.

What is the * operator in Rust?

The operands of all of these operators are evaluated in value expression context so are moved or copied. * Integer division rounds towards zero. ** Rust uses a remainder defined with truncating division. Given remainder = dividend % divisor , the remainder will have the same sign as the dividend.

What is an infix operator in R?

An infix operator allows a function to be called between two given arguments. A postfix operator just places the arguments prior to the function operation.

Does racket have infix operators?

k-infix makes writing infix expressions in Racket easy. It's extensible as one can add operators freely. k-infix supports prefix, postfix, and binary operators. Left and right -associativity are also supported.


1 Answers

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.

like image 173
DK. Avatar answered Oct 07 '22 06:10

DK.