F# 4.6 的新功能
F# 4.6 新增了對 F# 語言的多項改善。
開始使用
F# 4.6 適用於所有 .NET Core 散發套件和 Visual Studio 工具。 開始使用 F# 以深入了解。
匿名記錄
匿名記錄是 F# 4.6 中引進的新 F# 類型。 這些記錄不需要在使用之前就宣告的具名值簡單彙總。 您可以將其宣告為結構或參考型別。 根據預設其為參考型別。
open System
let getCircleStats radius =
let d = radius * 2.0
let a = Math.PI * (radius ** 2.0)
let c = 2.0 * Math.PI * radius
{| Diameter = d; Area = a; Circumference = c |}
let r = 2.0
let stats = getCircleStats r
printfn "Circle with radius: %f has diameter %f, area %f, and circumference %f"
r stats.Diameter stats.Area stats.Circumference
當您想要將實值型別分組並在效能敏感的情節中運作時,也可以將其宣告為結構:
open System
let getCircleStats radius =
let d = radius * 2.0
let a = Math.PI * (radius ** 2.0)
let c = 2.0 * Math.PI * radius
struct {| Diameter = d; Area = a; Circumference = c |}
let r = 2.0
let stats = getCircleStats r
printfn "Circle with radius: %f has diameter %f, area %f, and circumference %f"
r stats.Diameter stats.Area stats.Circumference
這些型別相當強大,且可用於許多情節。 深入了解匿名記錄。
ValueOption 函式
F# 4.5 中新增的 ValueOption 類型現在具有 Option 類型的「模組繫結函式同位」。 其中一些較常用的範例如下所示:
// Multiply a value option by 2 if it has value
let xOpt = ValueSome 99
let result = xOpt |> ValueOption.map (fun v -> v * 2)
// Reverse a string if it exists
let strOpt = ValueSome "Mirror image"
let reverse (str: string) =
match str with
| null
| "" -> ValueNone
| s ->
str.ToCharArray()
|> Array.rev
|> string
|> ValueSome
let reversedString = strOpt |> ValueOption.bind reverse
這可讓 ValueOption 與在具有實值型別可改善效能的情節中一樣使用 Option。
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應