Experimental support for operator overloading.
structs
can now have an additionalimpl operators for <struct-name>
sections. Functions defined in that section will server as operators for that struct- The following operator-functions are supported (at the moment):
- Unary operators (require one argument that has to be the struct-type):
neg
: The-a
operator aka "negate" aka "sign" aka "unary minus"
- Binary operators (require two arguments, at least one of them has to be the struct type):
add
: Thea + b
operatorsub
: Thea - b
operatormul
: Thea * b
operatordiv
: Thea / b
operatormod
: Thea % b
operatorpow
: Thea ** b
operator
- Unary operators (require one argument that has to be the struct-type):
Example:
pub struct NVector(values: float[]) {
dim: int = values.length
values: float[] = values
}
impl NVector {
sync fn add_scalar(self, scalar: float) -> NVector = NVector(self.values.map(fn(v) -> v + scalar))
sync fn mul_scalar(self, scalar: float) -> NVector = NVector(self.values.map(fn(v) -> v * scalar))
sync fn to_string(self) -> string = $"NVector({self.dim}, {self.values.to_string()})"
}
impl operators for NVector {
sync fn neg(right: NVector) -> NVector = NVector(right.values.map(fn(r) -> -r))
sync fn add(left: float, right: NVector) -> NVector = right.add_scalar(left)
sync fn add(left: NVector, right: float) -> NVector = left.add_scalar(right)
sync fn add(left: NVector, right: NVector) -> NVector = NVector((0..min_dim(left.dim, right.dim)).map(fn(i) -> left.values[i] + right.values[i]))
sync fn mul(left: float, right: NVector) -> NVector = right.mul_scalar(left)
sync fn mul(left: NVector, right: float) -> NVector = left.mul_scalar(right)
sync fn div(left: NVector, right: float) -> NVector = NVector(left.values.map(fn(l) -> l / right))
}
pub sync fn zero_nvector(dim: int) -> NVector = NVector((0..dim).map(fn(i) -> 0.0))
sync fn min_dim(dim1: int, dim2: int) -> int = if(dim1 < dim2) dim1 else dim2