Question

One feature I miss in from functional languages is the idea that operators are just functions, so adding a custom operator is often as simple as adding a function. Many procedural languages allow operator overloads, so in some sense operators are still functions (this is very true in D where the operator is passed as a string in a template parameter).

It seems that where operator overloading is allowed, it is often trivial to add additional, custom operators. I found this blog post, which argues that custom operators don't work nicely with infix notation because of precedence rules, but the author gives several solutions to this problem.

I looked around and couldn't find any procedural languages that support custom operators in the language. There are hacks (such as macros in C++), but that's hardly the same as language support.

Since this feature is pretty trivial to implement, why isn't it more common?

I understand that it can lead to some ugly code, but that hasn't stopped language designers in the past from adding useful features that can be easily abused (macros, ternary operator, unsafe pointers).

Actual use cases:

  • Implement missing operators (e.g. Lua doesn't have bitwise operators)
  • Mimic D's ~ (array concatenation)
  • DSLs
  • Use | as Unix pipe-style syntax sugar (using coroutines/generators)

I'm also interested in languages that do allow custom operators, but I'm more interested in why it has been excluded. I thought about forking a scripting language to add user-defined operators, but stopped myself when I realized that I haven't seen it anywhere, so there's probably a good reason why language designers smarter than me haven't allowed it.

No correct solution

Licensed under: CC-BY-SA with attribution
scroll top