17

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

1 Answer 1

27

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 *:
* / ÷ % & ⋅ ∘ × ∩ ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∗ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇
⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻
⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛ ⊍ ▷ ⨝ ⟕ ⟖ ⟗
Sign up to request clarification or add additional context in comments.

1 Comment

You could also technically use almost any other symbol as an infix operator with the power of macros! (if you really want to). I had an @infix hack (it relies on implicit multiplication by juxtaposition) that did this: julia> using InfixFunctions; @infix α(x, y) = x + y; 1 |α| 2. (InfixFunctions.jl was developed as a macro exercise for myself, it does not work with julia 1.x as is.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.