User-defined infix operator

I know operators in Julia are just standard functions, and I can use them using the ordinary prefix call syntax:

julia> +(1, 2)
3

However, they are also special in the sense that they can be (and are usually) used as infix operators:

julia> 1+2
3


Could I define my own infix operator? If so, how?

For example:

julia> α(x, y) = x+y
α (generic function with 1 method)

julia> α(1, 2)
3 # as expected

julia> 1α2
# expected result: 3
ERROR: UndefVarError: α2 not defined
Stacktrace:
 [1] top-level scope at REPL[5]:1

julia> 1 α 2
# expected result: 3
ERROR: syntax: extra token "α" after end of expression
Stacktrace:
 [1] top-level scope at REPL[5]:0

Upvotes: 17

Views: 4362

Answers (1)

As you said, operators are just standard functions, which you can define and otherwise manipulate like any other function. However, Julia's parser is configured to recognize a certain set of symbols as infix operators; if you define a function whose name is one of these symbols, it will be parsed as an infix operator.

For example:

julia> ⊕(x, y) = x+y
⊕ (generic function with 1 method)

# standard prefix function call
julia> ⊕(1, 2)
3

# infix operator call
julia> 1⊕2
3

julia> 1 ⊕ 2
3


The list of symbols recognized as infix operators (and associated precedence) can be found in the Julia parser source code. For the most part, this list is a subset of unicode category Sm(Symbol, math).

At the moment, it includes for example:

  • parsed with the same precedence as +:
+ - ⊕ ⊖ ⊞ ⊟ ∪ ∨ ⊔ ± ∓ ∔ ∸ ≏ ⊎ ⊻ ⊽ ⋎ ⋓ ⧺ ⧻ ⨈ ⨢ ⨣ ⨤ ⨥ ⨦
⨧ ⨨ ⨩ ⨪ ⨫ ⨬ ⨭ ⨮ ⨹ ⨺ ⩁ ⩂ ⩅ ⩊ ⩌ ⩏ ⩐ ⩒ ⩔ ⩖ ⩗ ⩛ ⩝ ⩡ ⩢ ⩣
  • parsed with the same precedence as *:
* / ÷ % & ⋅ ∘ × ∩ ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∗ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇
⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻
⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛ ⊍ ▷ ⨝ ⟕ ⟖ ⟗

Upvotes: 27

Related Questions