2014-11-24 32 views
0

以下兩個表達式產生相同的輸出:string.length減和連接的字符串

> ("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

回答

6

括號是重寫正常算符優先生成。在特定的功能&參數具有非常高的優先級,所以在後一種情況下它是被評價爲

(String.length "hello") + " " + "world!" 

,然後試圖將號碼添加到字符串。

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'