github untoldwind/KontrolSystem2 v0.5.9.1

latest releases: v0.5.9.5, v0.5.9.4, v0.5.9.3...
one month ago

Support for operator overloading.

  • structs can now have an additional impl 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: The a + b operator
      • sub: The a - b operator
      • mul: The a * b operator
      • div: The a / b operator
      • mod: The a % b operator
      • pow: The a ** b operator

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

Don't miss a new KontrolSystem2 release

NewReleases is sending notifications on new releases.