Posts Tagged “rust”

Proper Notation for Scalar Multiplication in Rust:
20190417
Dispatching on the RightHand 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. Objectoriented 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 righthand side object with the lefthand 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
.