为什么不将运算符同时作为关键字和函数呢?
Why not have operators as both keywords and functions?
我看到了 个问题,这让我很疑惑。
忽略几乎所有语言都必须向后兼容的事实,有什么理由我们不能将运算符同时用作关键字和函数,这取决于它是否紧跟括号?它会使语法更难吗?
我主要考虑 python,但也考虑 C 类语言。
根据语言的不同,未定义 not()。如果 not() 在某些语言中没有定义,则不能使用它。为什么 not() 没有用某种语言定义?因为该语言的创造者可能不需要这种语言结构。因为越简单越好。
Perl 做的事情与此非常相似,结果有时令人惊讶。您会在许多 Perl 文本中找到关于此的警告;例如,这个来自标准分布式 Perl 文档 (man perlfunc
):
Any function in the list below may be used either with or without parentheses around its arguments. (The syntax descriptions omit the parentheses.) If you use parentheses, the simple but occasionally surprising rule is this: It looks like a function, therefore it is a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter. Whitespace between the function and left parenthesis doesn't count, so sometimes you need to be careful:
print 1+2+4; # Prints 7.
print(1+2) + 4; # Prints 3.
print (1+2)+4; # Also prints 3!
print +(1+2)+4; # Prints 7.
print ((1+2)+4); # Prints 7.
一个更奇葩的案例,经常咬新人:
print
(a % 7 == 0 || a % 7 == 1) ? "good" : "bad";
将打印 0 或 1。
总之,看你的解析理论。许多人认为解析应该是精确和可预测的,即使这会导致令人惊讶的解析(如链接问题中的 Python 示例,或者更著名的是 C++ 的 most vexing parse)。其他人倾向于 Perl 的 "Do What I Mean" 哲学,即使结果——如上所述——有时与程序员的实际意图有很大不同。
C、C++ 和 Python 都倾向于 "precise and predictable" 哲学,现在不太可能改变。
我看到了
忽略几乎所有语言都必须向后兼容的事实,有什么理由我们不能将运算符同时用作关键字和函数,这取决于它是否紧跟括号?它会使语法更难吗?
我主要考虑 python,但也考虑 C 类语言。
根据语言的不同,未定义 not()。如果 not() 在某些语言中没有定义,则不能使用它。为什么 not() 没有用某种语言定义?因为该语言的创造者可能不需要这种语言结构。因为越简单越好。
Perl 做的事情与此非常相似,结果有时令人惊讶。您会在许多 Perl 文本中找到关于此的警告;例如,这个来自标准分布式 Perl 文档 (man perlfunc
):
Any function in the list below may be used either with or without parentheses around its arguments. (The syntax descriptions omit the parentheses.) If you use parentheses, the simple but occasionally surprising rule is this: It looks like a function, therefore it is a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter. Whitespace between the function and left parenthesis doesn't count, so sometimes you need to be careful:print 1+2+4; # Prints 7. print(1+2) + 4; # Prints 3. print (1+2)+4; # Also prints 3! print +(1+2)+4; # Prints 7. print ((1+2)+4); # Prints 7.
一个更奇葩的案例,经常咬新人:
print
(a % 7 == 0 || a % 7 == 1) ? "good" : "bad";
将打印 0 或 1。
总之,看你的解析理论。许多人认为解析应该是精确和可预测的,即使这会导致令人惊讶的解析(如链接问题中的 Python 示例,或者更著名的是 C++ 的 most vexing parse)。其他人倾向于 Perl 的 "Do What I Mean" 哲学,即使结果——如上所述——有时与程序员的实际意图有很大不同。
C、C++ 和 Python 都倾向于 "precise and predictable" 哲学,现在不太可能改变。