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 と同じように使用することができます。