Brackets as an operator

Is there a way to define an operator not as a symbol, but as brackets? An example: a commutator

[a::MyType, b::Mytype] = a*b - b*a

That syntax is already taken, [a, b] is a vector.

You can overload MyType[a, b]. I think it is less problematic than your syntax though the julia may internally use both syntax and get unintended side effects or even crash.

julia> struct Commutator end

julia> Base.getindex(::Type{Commutator}, a, b) = a*b - b*a

julia> Commutator[1, 2]
0

julia> Commutator[1.0, 2.0]
0.0
1 Like

There other brackets

{a,b}= a*b-b*a

With a macro, yes. Any valid syntax can be transformed into any other valid syntax. E.g. you could create @comm [a, b]. But it’s worth asking, very seriously, whether you get anything out of this transformation beyond “something cool”. That being said, this could be a good and manageably sized exercise to learn metaprogamming.

1 Like

Can it be defined without calling a macro? You don’t resort to macro with overpoaded operators.

You can do this, although it’s probably a terrible idea:

julia> struct MyType data end

julia> Base.vect(x::MyType, y::MyType) = "commutator of $x and $y, maybe"

julia> [MyType(1)]
1-element Array{MyType,1}:
 MyType(1)

julia> [MyType(1), MyType(2)]
"commutator of MyType(1) and MyType(2), maybe"

julia> [MyType(1), MyType(2), MyType(3)]
3-element Array{MyType,1}:
 MyType(1)
 MyType(2)
 MyType(3)

Since you own MyType, this shouldn’t break other code (the way that doing this for Matrix might). But it will confuse anyone trying to read it.

1 Like

That is overloading existing syntax, can it be done with other kind of brackets, like {}?

No, {}s are OK in the AST so a macro can deal with them, but they don’t lower to a method you could dispatch on.

FWIW an infix operator would be my first choice for anything like this. There are so many to choose from.

2 Likes

Isn’t there a style recommendation to avoid non-ascii characters in source,if possible?

Not that I am aware of.

Personally, I think that using Unicode chars is a neat feature of Julia and should be utilized when it makes sense. Which is especially the case for math operators.

3 Likes