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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With