下面的两个表达式产生相同的输出:
> ("hello" + " " + "world!");;
val it : string = "hello world!"
> "hello" + " " + "world!";;
val it : string = "hello world!"
为什么然后String.length
适用于第一个而不是第二个?
> String.length ("hello" + " " + "world!");;
val it : int = 12
> String.length "hello" + " " + "world!";;
String.length "hello" + " " + "world!";;
------------------------^^^
stdin(57,25): error FS0001: The type 'string' does not match the type 'int'
这是在FSI 14.0.22214.0
上生成的答案 0 :(得分:6)
括号覆盖正常的运算符优先级。特别是功能&参数具有非常高的优先级,因此在后一种情况下,它被评估为
(String.length "hello") + " " + "world!"
然后尝试在字符串中添加数字。
答案 1 :(得分:3)
这是因为函数绑定的次数比(+)运算符强。
> String.length "hello" + " " + "world!"
评估为:
> 5 + " " + "world!"
产生相同的错误:
> 5 + " " + "world!";;
5 + " " + "world!";;
----^^^
stdin(1,5): error FS0001: The type 'string' does not match the type 'int'