blade icon indicating copy to clipboard operation
blade copied to clipboard

Add support for operator overloading

Open mcfriend99 opened this issue 4 years ago • 3 comments

Is your feature request related to a problem? Please describe.

As it stands, Blade classes are first class and can be used in almost anything including iterables, values and more. It will greatly increase consistency to have Blade classes support operator overloading from classes.

Proposed Solution

Since today, Blade classes can become iterators by implementing the @iter and @itern decorators, Blade can employ decorators for operator overloading support.

E.g.

class A {
    @+(a2) {
        return self.value + a2.value
    }
}

var a1 = A()
a1.value = 5

var a2 = A()
a2.value = 7

echo a1 + a2

The above sample code should print 12 to terminal.

Alternative Solution

As an alternative, we could use a keyword operator.

For example:

class A {
    operator + {
        return self.value + __arg__.value
    }
}

var a1 = A()
a1.value = 5

var a2 = A()
a2.value = 7

echo a1 + a2

This will at best require an extra conditionally valid keyword __arg__.

mcfriend99 avatar Sep 01 '21 14:09 mcfriend99

I'm mostly for the operator keyword, but I'm not too familiar with the purpose of the @ character, which may or may not change my opinion.

As for the __arg__ keyword. Wren does this very nicely with an other keyword. So this could be:

class Point {
  Point(x, y) {
    self.x = x
    self.y = y
  }

  operator - {
    return Point(self.x - other.x, self.y - other.y)
  }
}

It feels very natural. It might also be important to keep negating values in mind (if this is to be implemented). So with your suggested syntax above, how would I do:

var p = Point(5, 2)
print(-p) /* should this work? */

Wren fixes this by having:

- {
  // negating
}

- (other) {
  // subtraction
}

benstigsen avatar Sep 15 '21 11:09 benstigsen

The @ character is used for creating decorators

mcfriend99 avatar Sep 16 '21 09:09 mcfriend99

Hmm, to me @-(other) {} does not seem to align with decorators. I think that introducing the keyword operator might be a good way to clarify different types of functionality.

benstigsen avatar Sep 16 '21 10:09 benstigsen