Custom binary operators (with custom name)?

Aside +, *, etc. is there a way to define my own binary operator, say Foo such that I can write something like:

Foo(x,y) = [some funny op using x and y]
((x Foo b) Foo c) ....

You’re looking for custom infix operators - see also ★ is not an operator.

In short - no.

2 Likes

Saw it.
Not even with a macro, e.g.

@opdef Foo(x,y) = [some funny op using x and y]
@op ((x Foo b) Foo c) ....

?

I think with macros you could build something similar. Just remember that a macro needs to take valid Julia syntax as input and (a foo b) is not valid syntax but e.g. [a foo b] would be. So in principle you could cobbled together something. However, in practice I would advise against using macros to bend a part of Julia’s core syntax to your will like this. It will quickly make your code incomprehensible to anybody else and probably contain all sorts of edge cases.

5 Likes

However, you have infinitely many choices available if you want to define a new infix operator: On adjoints and custom postfix and infix operators - #35 by stevengj

(And there is even a hack to make completely arbitrary identifiers like Foo act infix-like, though I wouldn’t recommend using it in production code: see Cursed Custom Infix Operators and InfixFunctions.jl.)

4 Likes

Oh my, I was not aware of these at all! Cursed indeed..

Just for the record, I think it might be helpful to note the list of characters that “can follow an operator and be parsed as part of the operator”, which I don’t find documented anywhere. At least as of this writing, the list seems to be here, which includes all Unicode combining characters (the categories Mn, Mc, and Me), as well as the explicit list of super- or sub-scripts and primes shown here.

(There is also a restriction to the range strictly between 0xA1 and 0x10ffff, but I think that’s just to make the checks more efficient, and doesn’t actually exclude any of the characters in those groups.)

It looks like most of these operators, except for the groups listed in this definition, can accept those suffixes.

2 Likes

Please feel free to submit a documentation patch — you can do that easily with the edit button directly on github.

1 Like

The range of valid Unicode codepoints is 0x00 to 0x10ffff, so this check only rejects outright invalid codepoints on the upper end, and the basic ASCII character set (0x00 - 0x7F) plus a few non-printing control characters on the lower end.

1 Like

PR here:

Related PR that came up because it’s impossible to make an operator with superscript alpha (\^alpha<tab>) here: