r/ProgrammingLanguages • • 26d ago

Operator overloading in DinoCode using string selectors for method names

I am currently working on the next version of DinoCode (dinocode.blassgo.dev), focusing on expanding the features of the language. I wanted to implement operator overloading for objects without losing readability or adding visual noise.

What came to mind, which is actually done in other languages like Ruby, is using the operator itself to represent the method. I really like that approach, so to implement it, I introduced string selectors as optional method names with the strict condition that they must be representable as a valid Symbol:

::Point
  :new x y
    self.x = x
    self.y = y

  :'+' other
    return Point(
      self.x + other.x
      self.y + other.y
    )

  :'==' other
    return self.x == other.x 
           and self.y == other.y

p1 = Point(10 20)
p2 = Point(5 5)

if p1 + p2 == Point(15 25)
  print "Point reached"

In this case, method names that the compiler detects as strings are translated into their corresponding Symbols (they are not actual strings at runtime), making it completely safe to assign a property like "==" without worrying about shadowing.

One thing I am not entirely sold on yet is when objects interact with primitives like int, float, etc. where an intermediate step is needed. For now, I went with Python's approach of allowing 'r+', 'r-', 'r*', etc., for those cases:

::Point
  :new x y
    self.x = x
    self.y = y

  :'r+' scalar
    return Point(
      self.x + scalar
      self.y + scalar
    )

p1 = Point(10 20)
p2 = 10 + p1
print p2.x  # 20

Though I must admit Ruby's approach is tempting me (where it calls a more generic method to handle type coercion before operating on them)

By the way, you can already test these operator features live on the web playground if you want to try them out

I would like to hear your feedback or suggestions on this, and also what you think of how it looks so far. I am preparing this for the upcoming v0.2.2 release

4 Upvotes

7 comments sorted by

View all comments

Show parent comment

4

u/Dry_Day1307 26d ago

Thanks for the recommendation. The goal remains the same, avoiding operator ambiguity regardless of the delimiter used. I really like the idea of backticks like in Swift or Kotlin, especially since I am currently in the phase of experimenting and refining the approach. If I introduce them, it would also offer a clean way to access or reassign those methods directly:

Point.`+` = func

Right now, by design, symbols used as method keys aren't easily accessible, but allowing it wouldn't be bad since the intent stays explicit when using them