How to create custom unary operator

Hello all.

Is there a way to create custom unary operators in Julia? (Not overload the predefined ones.)

The only place I’ve been able to find such discussion are:

and
https://github.com/JuliaLang/julia/issues/18139

The base language doesn’t provide a way to make arbitrary operators. While looking up a way, I found an approach that involved hacking the parser, but it was done for an old version of Julia.

I think the reason arbitrarily named custom operators aren’t a thing in Julia is the hassle of explicitly specifying operator characteristics like arity, precedence, associativity, short-circuiting, etc. Moreover, operators are often wordless like +, -, *, /, so their meaning and characteristics depend a lot on users’ familiarity, often from other contexts e.g. other languages, math. Custom ones won’t be familiar to most users, and if everyone was making their own, Julia could easily become unreadable in practice. Call syntax add(a, add(subtract(x, y), b) ) requires less memorization to understand than a %@^&% x %|_% y %@^&% b.

You’re not completely out of luck, though. Besides overloading the existing operators with their fixed characteristics, you can suffix an operator with primes, subscripts, and superscripts to make a new one. The new operator inherits the look and characteristics of the original operator, so familiarity is preserved.

1 Like

Thank you for the thorough response and the mentioned alternative, @Benny. You’re awesome!