问题描述
我知道Julia中的运算符只是标准函数,我可以通过以下方式使用它们普通的前缀调用语法:
I know operators in Julia are just standard functions, and I can use them usingthe 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
我可以定义自己的中缀运算符吗?如果是这样,怎么办?
例如:
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
推荐答案
正如您所说,运算符只是标准函数,您可以定义和定义否则像其他任何功能一样进行操作.但是,朱莉娅的解析器是配置为将某些符号集识别为中缀运算符;如果你定义一个名称为这些符号之一的函数,它将被解析为中缀运算符.
As you said, operators are just standard functions, which you can define andotherwise manipulate like any other function. However, Julia's parser isconfigured to recognize a certain set of symbols as infix operators; if youdefine a function whose name is one of these symbols, it will be parsed as aninfix operator.
例如:
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
可以找到被识别为中缀运算符的符号列表(以及相关的优先级)在朱莉娅中解析器源代码.为了大多数情况下,此列表是 unicode类别Sm 的子集(象征,数学).
The list of symbols recognized as infix operators (and associated precedence) can be found in the Juliaparser sourcecode. Forthe most part, this list is a subset of unicode category Sm(Symbol,math).
目前,它包括例如:
- 以与
+
相同的优先级进行解析:
- parsed with the same precedence as
+
:
+ - ⊕ ⊖ ⊞ ⊟ ∪ ∨ ⊔ ± ∓ ∔ ∸ ≏ ⊎ ⊻ ⊽ ⋎ ⋓ ⧺ ⧻ ⨈ ⨢ ⨣ ⨤ ⨥ ⨦
⨧ ⨨ ⨩ ⨪ ⨫ ⨬ ⨭ ⨮ ⨹ ⨺ ⩁ ⩂ ⩅ ⩊ ⩌ ⩏ ⩐ ⩒ ⩔ ⩖ ⩗ ⩛ ⩝ ⩡ ⩢ ⩣
- 具有与
*
相同的优先级: - parsed with the same precedence as
*
:
* / ÷ % & ⋅ ∘ × ∩ ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∗ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇
⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻
⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛ ⊍ ▷ ⨝ ⟕ ⟖ ⟗
这篇关于用户定义的中缀运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!