User-defined infix operator

后端 未结 1 560
梦如初夏
梦如初夏 2021-01-02 03:46

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

julia> +(1, 2)
3

Howeve

相关标签:
1条回答
  • 2021-01-02 04:10

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