为什么加号和一元加号在数组语法上会表现出奇怪的现象? [英] Why do the plus and unary plus behave strange in array syntax?
问题描述
在关于plus运算符的问题之后,我有一个后续问题.我们知道 plus
和 uplus
,因此1+2
解析为3
,就像1++2
甚至1++++++++2
一样.奇怪的事情发生在数组语法中,请考虑以下示例:
Following this question on the plus operator I have a follow-up question. We know the difference between plus
and uplus
, and thus that 1+2
resolves to 3
, just as 1++2
or even 1++++++++2
. The strange thing happens in array syntax, consider this example:
>> [1 ++ 2]
ans =
1 2 % Two unary plusses
>> [1 + + 2]
ans =
3 % A normal plus and a unary one
>> [1++2]
ans =
3 % A normal plus and a unary one
相同的方法适用于多个加号[1 +++..+++ 2]
,因此所有加号在中间连续产生[1 2]
,所有其他组合(据我测试)均为3
.
The same works with multiple plusses, [1 +++..+++ 2]
, so with all plusses consecutively in the middle generates [1 2]
, all other combinations (as far as I tested) result in 3
.
据我所知,空间在MATLAB中的重要性有限; exp(3*x/y)
与exp( 3 * x / y )
相同.它们在创建数组中有一个用途:[1 2]
会生成1个 -by- 2数组,还有其他一些用途,但是分隔运算符不是其中之一.
As far as I know spaces are of limited importance in MATLAB; exp(3*x/y)
is the same as exp( 3 * x / y )
. There is a use for them in creating arrays: [1 2]
will generate a 1 -by- 2 array, and there are a few other uses, but separating operators is not one of them.
因此,我的问题是:为什么[1 ++ 2]
和[1 + + 2]
的解析方式不同?
Therefore my question: Why do [1 ++ 2]
and [1 + + 2]
resolve differently?
请注意, minus
和 uminus
具有相同的行为,并且解析器非常神奇,足以将[1;;;3++ + + +--+ + ++4,;;;,;]
解析为[1;7]
.
Note that the minus
and uminus
have the same behaviour, and that the parser is magic enough to parse [1;;;3++ + + +--+ + ++4,;;;,;]
perfectly fine to [1;7]
.
推荐答案
我怀疑这与解析数字文字有关.特别是,请考虑以下复杂的示例:
My suspicion is that this has to do with how numeric literals are parsed. In particular, consider the following complex examples:
>> [1+2i]
ans =
1.0000 + 2.0000i
>> [1 +2i]
ans =
1.0000 + 0.0000i 0.0000 + 2.0000i
>> [1 + 2i]
ans =
1.0000 + 2.0000i
作为数组分隔符的空间与作为复数一部分的空间之间存在冲突.
There's a conflict between space as an array separator and space as a part of a complex number.
我相信解析器的编写应使其尽可能合理地理解复数(相对于复数数组).在解析涉及加/减和空格的表达式时,这很容易导致不平凡的行为.
I believe the parser was written such that it tries to make sense of complex numbers (versus complex arrays) as reasonably as possible. This can easily lead to non-trivial behaviour in parsing expressions involving addition/subtraction and whitespace.
更具体一点:
1 ++ 2
可能会解析为1 +2
,因为多个一元加号仍然是一元加号,并且一元加号只能对2
起作用.
1 ++ 2
might parse as 1 +2
, since multiple unary pluses are still a unary plus, and a unary plus can only act on the 2
.
但是1 + + 2
可能解析为1 + (+ 2)
,后者的加号被用作一元加号,而剩下的1 + 2
是单个复杂"数字.
But 1 + + 2
might parse as 1 + (+ 2)
where the latter plus is consumed as a unary plus, leaving 1 + 2
which is a single "complex" number.