Posts Tagged “rust”
-
Proper Notation for Scalar Multiplication in Rust:
2019-04-17
Dispatching on the Right-Hand Side of Operators and Rusts's Orphan RuleThe scalar multiplication in a vector space is written kv in math, where k is a scalar value (e.g. a number) and v is a vector. It would be nice to write
k * v
in programming languages, to stay close to the familiar notation. Object-oriented languages typically only support calling methods on the first argument. But the scalar normally doesn't know about vectors, so it can't easily do that.Python works around this with the
__rmul__
special method for defining the*
operator.__rmul__
is called on the right-hand side object with the left-hand side as the argument, the reverse of what__mul__
does. This works well, but feels a bit like a hack.In Rust each operator is defined via a single trait, for example the binary operator
More ...*
is defined viastd::ops::Mul
.