此 unit 類型是一種類型,表示沒有特定值;此 unit 類型只有單一值,當沒有任何其他值存在或需要時,做為佔位元。
語法
// The value of the unit type.
()
備註
每個 F# 運算式都必須評估為值。 對於不產生感興趣的值的表達式,會使用 型別 unit 的值。 此 unit 類型類似於 void C# 和 C++ 等語言的類型。
此 unit 類型具有單一值,且該值會以標記 ()表示。
型別的值 unit 通常用於 F# 程式設計,以保留語言語法需要值的位置,但不需要或需要值時。 例如,函式的 printf 傳回值。 由於作業的重要 printf 動作發生在函式中,因此函式不需要傳回實際值。 因此,傳回值的類型 unit為 。
有些建構需要值 unit 。 例如, do 模組最上層的系結或任何程式代碼預期會評估為 unit 值。 編譯程式會在模組最上層的 do 系結或程式代碼產生非使用值的結果 unit 時回報警告,如下列範例所示。
let function1 x y = x + y
// The next line results in a compiler warning.
function1 10 20
// Changing the code to one of the following eliminates the warning.
// Use this when you do want the return value.
let result = function1 10 20
// Use this if you are only calling the function for its side effects,
// and do not want the return value.
function1 10 20 |> ignore
此警告是功能性程序設計的特性;它不會出現在其他 .NET 程式設計語言中。 在純功能性程式中,函式沒有任何副作用,最後傳回值是函數調用的唯一結果。 因此,忽略結果時,可能是程序設計錯誤。 雖然 F# 不是純功能性程式設計語言,但最好盡可能遵循功能性程式設計樣式。