User-defined infix operator

扶醉桌前 提交于 2020-04-09 17:56:28

问题


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:


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


来源:https://stackoverflow.com/questions/60321301/user-defined-infix-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!